Nested defaultdict of defaultdict

前端 未结 8 2435
谎友^
谎友^ 2020-11-22 12:19

Is there a way to make a defaultdict also be the default for the defaultdict? (i.e. infinite-level recursive defaultdict?)

I want to be able to do:

x         


        
8条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 12:56

    I would also propose more OOP-styled implementation, which supports infinite nesting as well as properly formatted repr.

    class NestedDefaultDict(defaultdict):
        def __init__(self, *args, **kwargs):
            super(NestedDefaultDict, self).__init__(NestedDefaultDict, *args, **kwargs)
    
        def __repr__(self):
            return repr(dict(self))
    

    Usage:

    my_dict = NestedDefaultDict()
    my_dict['a']['b'] = 1
    my_dict['a']['c']['d'] = 2
    my_dict['b']
    
    print(my_dict)  # {'a': {'b': 1, 'c': {'d': 2}}, 'b': {}}
    

提交回复
热议问题