Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python pprint nested dictionary newline each nesting?

Tags:

python

I have the following datastucture:

{'row_errors': {'hello.com': {'template': [u'This field is required.']}}}

When I use pprint in python, I am getting

{'row_errors': {'hello.com': {'template': [u'This field is required.']}}}

However, I would very much like it to be printed like:

{'row_errors': 
    {'hello.com': 
        {'template': [u'This field is required.']}}}

Is this possible to configure via pprint? (I prefer pprint because I am printing this inside a jinja template).

like image 561
Tinker Avatar asked Jun 29 '17 18:06

Tinker


People also ask

How do you flatten a dictionary with nested lists and dictionaries in Python?

Basically the same way you would flatten a nested list, you just have to do the extra work for iterating the dict by key/value, creating new keys for your new dictionary and creating the dictionary at final step. For Python >= 3.3, change the import to from collections.

How do you pop a nested dictionary in Python?

Deleting dictionaries from a Nested Dictionary Deletion of dictionaries from a nested dictionary can be done either by using del keyword or by using pop() function.


1 Answers

Like the wim suggested on comments, you can use json.dump.

Quoting from Blender's answer, you can achieve this like this:

The json module already implements some basic pretty printing with the indent parameter:

>>> import json
>>>
>>> your_json = '["foo", {"bar":["baz", null, 1.0, 2]}]'
>>> parsed = json.loads(your_json)
>>> print json.dumps(parsed, indent=4, sort_keys=True)
[
    "foo", 
    {
        "bar": [
            "baz", 
            null, 
            1.0, 
            2
        ]
    }
]
like image 200
mdegis Avatar answered Sep 21 '22 13:09

mdegis