Retrieve the value of the nested key indicated by the given selector list from a dictionary or list.

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
  1. From functools import reduce.
  2. From operator import getitem.
  3. Take a nested dictionary as input.
  4. Create a function to retrieve the value of the nested key indicated by the given selector list from a dictionary.
  5. Give 2 parameters to the function as input one is the dictionary and the second is the selectors.
  6. Using reduce and getitem retrieve the value of the nested key indicated by the given selector.
  7. 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
				
			

group the elements of a given list based on the given function.

show a dictionary with a maximum count of pairs.

Leave a Comment