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?
A defaultdict works exactly like a normal dict, but it is initialized with a function (“default factory”) that takes no arguments and provides the default value for a nonexistent key. A defaultdict will never raise a KeyError. Any key that does not exist gets the value returned by the default factory.
As of Python 3.6 this will be unnecessary, as all dicts , and therefore all defaultdicts , will be ordered. I am ok with it not working on 3.5 ;) Though dicts in CPython 3.6 preserve order, it is an implementation detail not to be relied upon, see stackoverflow.com/a/39980548/91243.
The main difference between defaultdict and dict is that when you try to access or modify a key that's not present in the dictionary, a default value is automatically given to that key . In order to provide this functionality, the Python defaultdict type does two things: It overrides .
I've used pprint(dict(defaultdict))
before as a work-around.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With