The topic is not new and has already been discussed in multiple posts (links at the bottom). However, I felt like the resources are scattered and it is not always clear what the the best approach is. I would also like to introduce some constraints to clearly define the behaviour that I am expecting.
Say we have a nested dictionary with any number of items and arbitrary depth:
d = {"a": {"b": {"c" : 0}},
"b": {"c" : 1},
"c": 2}
What is the best way to get its items?
The naive approach is quite cumbersome, especially when there are many nested levels.
>>> d["a"]["b"]["c"]
0
So the first constraint is that the keys of the items to get must be provided as tuples, for example:
key = ("a", "b", "c")
The objective now is to create some function that works as follows:
>>> getitem(d, key)
0
This format can also conveniently be applied directly as the __getitem__ method of a class.
One more constraint: I want the function to fail noisily when it is asked to get a non-existing key.
>>> getitem(d, ("asd",))
...
KeyError: 'asd'
This excludes all solutions that use item getting to vivify the dictionary.
Finally, please provide low-level code if possible. If you know of a package that solves this problem please explain the underlying mechanism.
References
- What is the best way to implement nested dictionaries?
- Access nested dictionary items via a list of keys?
- Nested dictionaries in python with error when accessing non-existent key
- Safe method to get value of nested dictionary
- Accessing values nested within dictionaries
- python: what are efficient techniques to deal with deeply nested data in a flexible manner?
- Convenient way to handle deeply nested dictionary in Python
- Good way to retrieve list of nested keys?
- What is the fastest way to return a specific list within a dictionary within a dictionary?