Python – 提取 K 键值的第 i 个元素
给定一个字典,提取 K 键值列表的第 i 个元素。
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.
方法:使用 + get()
这是可以执行此任务的方式之一。在此,我们使用 get() 提取键的值,然后在检查 K 是否小于列表长度后提取值。
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))
输出
The original dictionary is : {'Gfg': [6, 7, 3, 1], 'is': [9, 1, 4], 'best': [10, 7, 4]}
The extracted value : 3