Reputation: 25
I'm trying to perform several lookups in a dictionary, some of which may be lookups to subdictionaries (d['a'], d['b']['c']['d']['e']
). I'd like to return a default value on KeyError
at any point in the lookup process, whether it be on the first or nth dictionary. The end goal is to put the return values in a new, flattened dictionary.
Is there a simpler way of doing this than my current:
e = {}
try:
e['a'] = d['a']
except KeyError:
e['a'] = 0
try:
e['d'] = d['b']['c']['d']
except KeyError:
e['d'] = 0
...and so on
I've thought about the issue some and considered using .get()
or using defaultdict()
or using some sort of recursion, but couldn't come up with any solutions. Thanks in advance for the help!
Upvotes: 0
Views: 218
Reputation: 184191
Break that out into a function:
def try_get(dic, default, *keys):
for key in keys:
try:
dic = dic[key]
except KeyError:
return default
return dic
e['a'] = try_get(d, 0, 'a')
e['d'] = try_get(d, 0, 'b', 'c', 'd')
Upvotes: 2