Python and default dict, how to pprint

Question:

I am using default dict. I need to pprint.

However, when I pprint …this is how it looks.

defaultdict(<functools.partial object at 0x1f68418>, {u'300:250': defaultdict(<functools.partial object at 0x1f683c0>, {0: defaultdict(<type 'list'>, {u'agid1430864021': {u'status': u'0', u'exclude_regi..........

How to I get pprint to work with default dict?

Asked By: Tampa

||

Answers:

I’ve used pprint(dict(defaultdict)) before as a work-around.

Answered By: Jon Clements

In the same vein as Jon Clements’ answer, if this is a common operation for you, you might consider subclassing defaultdict to override its repr method, as shown below.

Input:

from collections import defaultdict

class prettyDict(defaultdict):
    def __init__(self, *args, **kwargs):
        defaultdict.__init__(self,*args,**kwargs)

    def __repr__(self):
        return str(dict(self))

foo = prettyDict(list)

foo['bar'].append([1,2,3])
foo['foobar'].append([4,5,6,7,8])

print(foo)

Output:

{'foobar': [[4, 5, 6, 7, 8]], 'bar': [[1, 2, 3]]}
Answered By: Mr. Squig

The best solution I’ve found is a bit of a hack, but an elegant one (if a hack can ever be):

class PrettyDefaultDict(collections.defaultdict):
    __repr__ = dict.__repr__

And then use the PrettyDefaultDict class instead of collections.defaultdict. It works because of the way the pprint module works (at least on 2.7):

r = getattr(typ, "__repr__", None)
if issubclass(typ, dict) and r is dict.__repr__:
    # follows pprint dict formatting

This way we “trick” pprint into thinking that our dictionary class is just like a normal dict.

Answered By: RedGlow

I really like this solution for dealing with nested defaultdicts. It’s a bit of a hack, but does the job neatly when pdbing:

import json
data_as_dict = json.loads(json.dumps(data_as_defaultdict))
print(data_as_dict)

From: https://stackoverflow.com/a/32303615/4526633

Answered By: jarekwg

If you don’t have to use pprint, you can use json to pretty-print the defaultdict:

print(json.dumps(my_default_dict, indent=4))

This also works for nested defaultdicts.

Answered By: Markus
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.