The Python Oracle

How to pretty print nested dictionaries?

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Riding Sky Waves v001

--

Chapters
00:00 How To Pretty Print Nested Dictionaries?
00:30 Accepted Answer Score 227
00:46 Answer 2 Score 886
01:04 Answer 3 Score 117
01:29 Answer 4 Score 96
01:43 Thank you

--

Full question
https://stackoverflow.com/questions/3229...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #dictionary

#avk47



ANSWER 1

Score 886


My first thought was that the JSON serializer is probably pretty good at nested dictionaries, so I'd cheat and use that:

>>> import json
>>> print(json.dumps({'a':2, 'b':{'x':3, 'y':{'t1': 4, 't2':5}}},
...                  sort_keys=True, indent=4))
{
    "a": 2,
    "b": {
        "x": 3,
        "y": {
            "t1": 4,
            "t2": 5
        }
    }
}



ACCEPTED ANSWER

Score 227


I'm not sure how exactly you want the formatting to look like, but you could start with a function like this:

def pretty(d, indent=0):
   for key, value in d.items():
      print('\t' * indent + str(key))
      if isinstance(value, dict):
         pretty(value, indent+1)
      else:
         print('\t' * (indent+1) + str(value))



ANSWER 3

Score 117


You could try YAML via PyYAML. Its output can be fine-tuned. I'd suggest starting with the following:

print(yaml.dump(data, allow_unicode=True, default_flow_style=False))

The result is very readable; it can be also parsed back to Python if needed.

Edit:

Example:

>>> import yaml
>>> data = {'a':2, 'b':{'x':3, 'y':{'t1': 4, 't2':5}}}
>>> print(yaml.dump(data, default_flow_style=False))
a: 2
b:
  x: 3
  y:
    t1: 4
    t2: 5



ANSWER 4

Score 96


By this way you can print it in pretty way for example your dictionary name is yasin

import json

print (json.dumps(yasin, indent=2))

or, safer:

print (json.dumps(yasin, indent=2, default=str))