Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

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 dictionary
test_dict = {'Gfg' : [6, 7, 3, 1],
             'is' : [9, 1, 4],
             'best' : [10, 7, 4]}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# initializing K
K = 'Gfg'
 
# initializing i
i = 2
 
# using get() to get the required value
temp = test_dict.get(K)
res = None
# checking for non empty dict and length constraints
if temp and len(temp) >= i:  
        res = temp[i]
         
# printing result
print("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
Recommended Articles
Page :

Start Your Coding Journey Now!