format dictionary for with new lines and tabs when converting to string?

75 Views Asked by At

Is there a simple way to format a string of a dictionary?

I have a dictionary that I want to save into a file, to do this I am passing it to the file as a string using str(dictionary).

This means that the dictionary looks like this in the file, just one long line:

meals = {'chilli': {'ingredients': {'vegetarian mince': 500, 'tin of tomatoes': 1, 'red onion': 1}, 'prep_time': 1, 'storage_time': 3, ...

However, I would like it to be formatted like this, for readability, with new lines and tabs to reflect the hierarchy:

meals = {
    'chilli': {
        'ingredients': {'vegetarian mince': 500, 'tin of tomatoes': 1, 'red onion': 1},
        'prep_time': 1,
        'storage_time': 3,
        ...

Is there a simple/best practice way to achieve this?

I have been able to achieve some of this but not all of it with .replace() and could probably manage it all through a lot of iterating through the dictionary but was wondering if there was a better way, .replace() and iterating through the dictionary both feel clunky and/or are difficult to achieve exactly what I want.

1

There are 1 best solutions below

1
Supertech On

How about pprint.

import pprint
meals = {...}
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(meals)