Nested defaultdict of defaultdict

前端 未结 8 2333
谎友^
谎友^ 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': {}}
    
    0 讨论(0)
  • 2020-11-22 12:58

    here is a recursive function to convert a recursive default dict to a normal dict

    def defdict_to_dict(defdict, finaldict):
        # pass in an empty dict for finaldict
        for k, v in defdict.items():
            if isinstance(v, defaultdict):
                # new level created and that is the new value
                finaldict[k] = defdict_to_dict(v, {})
            else:
                finaldict[k] = v
        return finaldict
    
    defdict_to_dict(my_rec_default_dict, {})
    
    0 讨论(0)
提交回复
热议问题