Home >Backend Development >Python Tutorial >How to Create an Infinitely-Nested defaultdict in Python?
How to Create an Infinite-Level Recursive defaultdict
Python's defaultdict is a versatile data structure that can be used to create nested dictionaries. However, by default, defaultdicts only provide a single level of nesting. Is there a way to create a defaultdict that behaves as the default factory for inner defaultdicts, effectively creating an infinite-level recursive structure?
The original question sought to achieve the following behavior:
x = defaultdict(...stuff...) x[0][1][0] # Should return an empty dictionary {}
Using only the native defaultdict arguments, it is not possible to create an infinitely-nested recursive defaultdict. The popular workaround is to utilize a lambda function:
x = defaultdict(lambda: defaultdict(dict))
This approach creates a defaultdict that generates a new defaultdict when accessing a missing key. This effectively provides infinite levels of nesting.
Advantages of the Lambda-Based Approach:
Note:
The infinitely-nested defaultdict using lambda has the following characteristics:
The above is the detailed content of How to Create an Infinitely-Nested defaultdict in Python?. For more information, please follow other related articles on the PHP Chinese website!