Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python and default dict, how to pprint

Tags:

python

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?

like image 207
Tampa Avatar asked Oct 16 '12 23:10

Tampa


People also ask

How does default dict work in Python?

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.

Is default dict ordered?

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.

What is the difference between default dict and dict?

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 .


2 Answers

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

like image 75
Jon Clements Avatar answered Oct 18 '22 00:10

Jon Clements


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.

like image 32
RedGlow Avatar answered Oct 18 '22 01:10

RedGlow