Nested defaultdict of defaultdict

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

    The other answers here tell you how to create a defaultdict which contains "infinitely many" defaultdict, but they fail to address what I think may have been your initial need which was to simply have a two-depth defaultdict.

    You may have been looking for:

    defaultdict(lambda: defaultdict(dict))
    

    The reasons why you might prefer this construct are:

    • It is more explicit than the recursive solution, and therefore likely more understandable to the reader.
    • This enables the "leaf" of the defaultdict to be something other than a dictionary, e.g.,: defaultdict(lambda: defaultdict(list)) or defaultdict(lambda: defaultdict(set))

提交回复
热议问题