Python and default dict, how to pprint

后端 未结 5 1939
面向向阳花
面向向阳花 2020-12-28 13:37

I am using default dict. I need to pprint.

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

defaultdict(

        
相关标签:
5条回答
  • 2020-12-28 13:42

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

    0 讨论(0)
  • 2020-12-28 13:44

    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]]}
    
    0 讨论(0)
  • 2020-12-28 13:47

    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.

    0 讨论(0)
  • 2020-12-28 13:54

    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.

    0 讨论(0)
  • 2020-12-28 14:02

    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

    0 讨论(0)
提交回复
热议问题