Nested defaultdict of defaultdict

前端 未结 8 2446
谎友^
谎友^ 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:32

    I based this of Andrew's answer here. If you are looking to load data from a json or an existing dict into the nester defaultdict see this example:

    def nested_defaultdict(existing=None, **kwargs):
        if existing is None:
            existing = {}
        if not isinstance(existing, dict):
            return existing
        existing = {key: nested_defaultdict(val) for key, val in existing.items()}
        return defaultdict(nested_defaultdict, existing, **kwargs)
    

    https://gist.github.com/nucklehead/2d29628bb49115f3c30e78c071207775

提交回复
热议问题