Reputation: 943
I would like to define a little wrapper function that takes some sort of 'path' to access different levels of nested dictionaries:
D = {'key1': valueA,
'key2': {'key21': valueB,
{'key22': valueC}
In this simple example, I'd like to write a function that as argument takes, for example, a tuple like
dict_path = ('key2', 'key22')
>>>nested_getter(dict_path)
valueC
Upvotes: 2
Views: 82
Reputation: 76755
D = {'key1': valueA,
'key2': {'key21': valueB,
'key22': valueC}}
def nested_getter(root, path):
for elem in path:
root = root[elem]
return root
With this you can do:
>>> nested_getter(D, ('key2', 'key22'))
3
Upvotes: 4