In this python dictionary program, we will retrieve the value of the nested key indicated by the given selector list from a dictionary or list.
Steps to solve the program
- From functools import reduce.
- From operator import getitem.
- Take a nested dictionary as input.
- Create a function to retrieve the value of the nested key indicated by the given selector list from a dictionary.
- Give 2 parameters to the function as input one is the dictionary and the second is the selectors.
- Using reduce and getitem retrieve the value of the nested key indicated by the given selector.
- Print the output.
from functools import reduce
from operator import getitem
D1 = {'p1':{'name':{'first':'lionel','last':'messi'},'team':['psg','argentina']}}
def retrive(d, selectors):
return reduce(getitem, selectors, d)
print(retrive(D1, ['p1','name','last']))
print(retrive(D1, ['p1','team', 1]))
Output :
messi
argentina