Nested defaultdict of defaultdict

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

    @nucklehead's response can be extended to handle arrays in JSON as well:

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

提交回复
热议问题