1

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 is no easy way to get exactly what you want, because it's isn't consistent -- you have `'chili'` and its value dict on separate lines, but then you have `'ingredients'` and its value dict on the _same_ line. – John Gordon Dec 28 '22 at 18:28
  • 3
    Using `json.dump()` with the optional `indent` argument will get you mostly what you want, with a minimum of extra coding. – John Gordon Dec 28 '22 at 18:29
  • 1
    Do you really want to include the `meals =` part of this? – ChrisGPT was on strike Dec 28 '22 at 18:29
  • @JohnGordon thank you, I don’t need it exactly had my example, just so I can read it so .dump() will work – superdupersolly Dec 28 '22 at 18:41
  • @Chris I do need this as I then import the file and access the dictionary as a variable, however it’s easy to add after formatting. – superdupersolly Dec 28 '22 at 18:42
  • 1
    ...so you're trying to dynamically generate a Python file? This definitely sounds like [an XY problem](https://meta.stackexchange.com/q/66377/248627). Store data as pure data. That can be in a JSON file, a database, etc. – ChrisGPT was on strike Dec 28 '22 at 18:43

1 Answers1

0

How about pprint.

import pprint
meals = {...}
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(meals)
Supertech
  • 746
  • 1
  • 9
  • 25