Nested defaultdict of defaultdict

前端 未结 8 2436
谎友^
谎友^ 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: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, {})
    

提交回复
热议问题