Suppose I have a dictionary that is nested arbitrarily:
d = {
11: {
21: {31: 'a', 32: 'b'},
22: {31: 'a', 34: 'c'},
},
12: {
1: {2: 3}
}
}
And a list of keys whose position tells me which nested dictionary to look for every key in:
keys = [11, 21, 31]
# keys = [11, 23, 44]
Is there a simple one liner to do this? I've looked at the questions listed below, and they are similar, but not really what I'm looking for. I have also attempted it myself and came up with this:
from functools import reduce
def lookup(d, key):
return d.get(key, {}) if d and isinstance(d, dict) else None
def fn(keys, d):
return reduce(lookup, keys, d)
print(fn(keys, d)) # prints 'a'
The problem with this, is that in case of second list of keys (see commented out keys), it continues looking up nested keys further, even though the higher level key wasn't found, and continuing is pointless. How can I stop reduce
as soon as I find a final match or fail (one of the questions listed below addresses it, but I can't really apply it in my use case... or can I?)? Any other ideas? Oh and I want to accomplish this using official python libraries only. So no numpy
, pandas
etc, but functools
, itertools
are fine
Python: Convert list to dict keys for multidimensional dict with exception handling
Is there a simple one-liner for accessing each element of a nested dictioanry in Python?
Accessing nested values in nested dictionaries in Python 3.3
Using itertools for recursive function application
Stopping a Reduce() operation mid way. Functional way of doing partial running sum
Finding a key recursively in a dictionary
Thanks!