July 12: Value from Nested Dicts/List
Last updated: Oct 9, 2024
Contents
Hey readers, thanks for coming back here. While working on one of the bugfixes for a new project, I came across an interesting piece of code written by one of my colleague. The basic idea is of the problem is to get a value from dict with lots of nested objects, about 5-6 levels deep. There are quite a few variants of dict that we get, but for a variation, path of keys is same. For an example, consider the following dict.
example = {
"key1": {
"key2": {
"key3": [
{
"key4": {
"required": "value"
}
}
]
}
}
}
Let’s say we have multiple variants of the json with similar structure where you need to get the required
value. One way to do it would be to directly get the data from the dict.
example["key1"]["key2"]["key3"][0]["key4"]["required"]
While this is totally fine, doing this for many variation is tedious.
The following function I think is very good approach to make it easier.
from functools import reduce
def get_value_from_dict(data: dict, path: Iterable[str | int]) -> Any:
return reduce(lambda curr, key: curr[key], path, data)
And then function is called as below
get_value_from_dict(example, ("key1", "key2", "key3", 0, "key4", "required"))
which I believe looks much cleaner and less tedious compared to previous approach.