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
}
}
}
Answer from Ken on Stack OverflowMy 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
}
}
}
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))
pretty printing dictionaries and evaluating strings into dicts
Help to improve to this custom dict printing (or formatting) function?
Pretty Print Dictionary
Printing a dictionary
I know it's a pain to print these out, especially if they're deeply-nested and scrolling off the screen. This was something I tried and tried to hack around for a while, until I saw this guy's approach. This is actually a good learning point for hasattr and isinstance too. Check this out.
http://ze.phyr.us/python-dict-repr/
And then there's ast.literal_eval, which can be used to evaluate (safely) strings, turning them into dictionaries, if they're formatted properly. Cool! Have you guys used either of these in your projects?
I almost forgot how useful this one can be for dictionary, JSON and API work. Repost of something I developed last year.
Ever have trouble reading a dictionary or JSON data? I've been using dictionaries a lot lately and I got tired of having to copy/paste them to a website so I could read them. So taking advantage of the ability to run JavaScript in a shortcut using HTML, I give you... the Pretty Print Dictionary!
All you have to do is grab/create a dictionary, call this shortcut, and voila! An easy to read dictionary will be shown to you. Once you close the pop up, it will return the original data back so your original shortcut can continue running.
User u/Schl3ck extended my original work last year. If you pass the dictionary as part of a list, the remaining words in the list will be highlighted. You have to see it in action to appreciate how easy it makes finding a word in a huge amount of data.
Here’s the shortcut:
https://www.icloud.com/shortcuts/f73609147b8d4a888316c6e81a95cc94
And here’s an example shortcut that shows you how to use it:
https://www.icloud.com/shortcuts/4b0d038d93ef4e3abf613bf6212873b5
Enjoy!