Sometimes, we want to access nested dictionary items via a list of keys with Python.
In this article, we’ll look at how to access nested dictionary items via a list of keys with Python.
How to access nested dictionary items via a list of keys with Python?
To access nested dictionary items via a list of keys with Python, we can use the reduce
function with the operator.getitem
method to get the dictionary item with the array of keys forming the path to the dictionary item.
For instance, we write:
from functools import reduce
import operator
def getFromDict(data_dict, map_list):
return reduce(operator.getitem, map_list, data_dict)
def setInDict(data_dict, map_list, value):
getFromDict(data_dict, map_list[:-1])[map_list[-1]] = value
data_dict = {
"a": {
"r": 1,
"s": 2,
"t": 3
},
"b": {
"u": 1,
"v": {
"x": 1,
"y": 2,
"z": 3
},
"w": 3
}
}
map_list = ["a", "r"]
setInDict(data_dict, map_list, 100)
print(data_dict)
We have the getFromDict
function that calls reduce
with the mapList
and dataDict
to get the item from data_dict
with the path of the dictionary formed by map_list
list.
Then we have the setInDict
function that use getFromDict
with the data_dict
and map_list
to get dictionary item from data_dict
with the path to the item formed by map_list
.
Then we set the value of the retrieved dictionary item to value
.
Next, we call setInDict
with data_dict
, map_list
and 100 to set data_list['a']['r']
to 100.
Therefore, data_dict
is now:
{'a': {'r': 100, 's': 2, 't': 3}, 'b': {'u': 1, 'v': {'x': 1, 'y': 2, 'z': 3}, 'w': 3}}
Conclusion
To access nested dictionary items via a list of keys with Python, we can use the reduce
function with the operator.getitem
method to get the dictionary item with the array of keys forming the path to the dictionary item.