Nested defaultdict of defaultdict

前端 未结 8 2432
谎友^
谎友^ 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 12:44

    For an arbitrary number of levels:

    def rec_dd():
        return defaultdict(rec_dd)
    
    >>> x = rec_dd()
    >>> x['a']['b']['c']['d']
    defaultdict(, {})
    >>> print json.dumps(x)
    {"a": {"b": {"c": {"d": {}}}}}
    

    Of course you could also do this with a lambda, but I find lambdas to be less readable. In any case it would look like this:

    rec_dd = lambda: defaultdict(rec_dd)
    

提交回复
热议问题