Python – Extract ith element of K key’s value

• Last Updated : 11 Sep, 2021

Given a dictionary, extract ith element of K key’s value list.

Input : test_dict = {‘Gfg’ : [6, 7, 3, 1], ‘is’ : [9, 1, 4], ‘best’ : [10, 7, 4]}, K = ‘Gfg’, i = 1
Output : 7
Explanation : 1st index of ‘Gfg”s value is 7.

Input : test_dict = {‘Gfg’ : [6, 7, 3, 1], ‘is’ : [9, 1, 4], ‘best’ : [10, 7, 4]}, K = ‘best’, i = 0
Output : 10
Explanation : 0th index of ‘best”s value is 10.

Method : Using + get()

This is one of the ways in which this task can be performed. In this, we extract the key’s value using get() and then value is extracted after checking for K being less than list length.

Python3

 # Python3 code to demonstrate working of# Extract ith element of K key's value# Using get() # initializing dictionarytest_dict = {'Gfg' : [6, 7, 3, 1],             'is' : [9, 1, 4],             'best' : [10, 7, 4]} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # initializing KK = 'Gfg' # initializing ii = 2 # using get() to get the required valuetemp = test_dict.get(K)res = None# checking for non empty dict and length constraintsif temp and len(temp) >= i:          res = temp[i]         # printing resultprint("The extracted value : " + str(res))
Output
The original dictionary is : {'Gfg': [6, 7, 3, 1], 'is': [9, 1, 4], 'best': [10, 7, 4]}
The extracted value : 3
My Personal Notes arrow_drop_up