12

There are many Python questions on how to do an infinitely-nested/recursive defaultdict, which one(s) should be canonical?

  1. Nested insertion/creation of dictionary
  2. Multi-level defaultdict with variable depth?
  3. Is there a standard class for an infinitely nested defaultdict? [No, but it's typically a one-liner]
  4. Recommended Nested defaultdict of defaultdict
  5. ...please add to this list...

Known duplicates:

  1. Python3.6 4-level dictionaries giving KeyError [duplicate]

Related but distinct:

  1. Can't pickle recursive nested defaultdict
  2. PERL-like autovivification with default value in Python, and returns a default value from non-existing arbitrary nesting?
  3. Set Python dict items recursively, when given a compound key 'foo.bar.baz'
  4. How to convert dict into recursive defaultdict and load JSON?

and even:

2
  • 1
    This might be worth putting onto the related but distinct list: What is the best way to implement nested dictionaries? - has a great answer, but not strictly a dup.
    – jpp
    Jan 7, 2019 at 10:21
  • @jpp: Sure, you (and anyone else) have my blessing to edit any bona-fide related-but-distinct into the list, with an URL, also please explain tersely in-line why (the question or its answers) are distinct (in this case: because they're only concerned with (non-infinite) n-level dictionaries, so they don't strictly need defaultdict or recursion, although it would still be a solution, and arguably the 'best' solution, unless performance-critical). Also, distrust old performance numbers from 2013/ Python 2.7.4 or so, hence the recommendation to prefer setdefault
    – smci
    Jan 7, 2019 at 10:32

1 Answer 1

4

My opinion is (2) Multi-level defaultdict with variable depth? & (4) defaultdict of defaultdict, nested are good canonicals. They have good, highly upvoted answers and have stood the test of time. In addition, many posts have already been marked duplicates of these.

In fact, I believe these 2 questions should be merged. The only "keyword" discrepancy for Google is the former uses "Multi-level" and the latter uses "Nested". I'm confident a question can be phrased which, at least in the body and possibly even in the title, utilizes both these terms.

I generally see reluctance to merge questions, but I think this is a clear case where it is warranted, as every answer on both posts is applicable to either question.

The other options you put forward, (1) & (3), don't seem as generalized.

2
  • Thanks. Any opinion which of 2), 4) should be primary? 4) "Nested defaultdict of defaultdict" sounds clearer to me
    – smci
    Jan 7, 2019 at 9:59
  • 1
    @smci, I'd prefer (4) since it gives a working example of a one-level nested defaultdict and explicitly asks for extension. While (2) is more a problem statement.
    – jpp
    Jan 7, 2019 at 10:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .