Python – 从混合字典列表中提取键的值
给定一个字典列表,每个字典都有不同的键,提取键 K 的值。
Input : test_list = [{“Gfg” : 3, “b” : 7}, {“is” : 5, ‘a’ : 10}, {“Best” : 9, ‘c’ : 11}], K = ‘b’
Output : 7
Explanation : Value of b is 7.
Input : test_list = [{“Gfg” : 3, “b” : 7}, {“is” : 5, ‘a’ : 10}, {“Best” : 9, ‘c’ : 11}], K = ‘c’
Output : 11
Explanation : Value of c is 11.
方法#1:使用列表推导
这是可以执行此任务的方式之一。在此,我们迭代列表中的每个字典,并检查其中的键,如果存在则返回所需的值。
Python3
# Python3 code to demonstrate working of
# Extract Key's value from Mixed Dictionaries List
# Using list comprehension
# initializing list
test_list = [{"Gfg" : 3, "b" : 7},
{"is" : 5, 'a' : 10},
{"Best" : 9, 'c' : 11}]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 'Best'
# list comprehension to get key's value
# using in operator to check if key is present in dictionary
res = [sub[K] for sub in test_list if K in sub][0]
# printing result
print("The extracted value : " + str(res))
Python3
# Python3 code to demonstrate working of
# Extract Key's value from Mixed Dictionaries List
# Using update() + loop
# initializing list
test_list = [{"Gfg" : 3, "b" : 7},
{"is" : 5, 'a' : 10},
{"Best" : 9, 'c' : 11}]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 'Best'
res = dict()
for sub in test_list:
# merging all Dictionaries into 1
res.update(sub)
# printing result
print("The extracted value : " + str(res[K]))
输出
The original list : [{'Gfg': 3, 'b': 7}, {'is': 5, 'a': 10}, {'Best': 9, 'c': 11}]
The extracted value : 9
方法 #2:使用 update() + 循环
这是可以执行此任务的另一种方式。在此,我们将每个字典相互更新。形成一个大字典,然后从这个字典中提取值。
Python3
# Python3 code to demonstrate working of
# Extract Key's value from Mixed Dictionaries List
# Using update() + loop
# initializing list
test_list = [{"Gfg" : 3, "b" : 7},
{"is" : 5, 'a' : 10},
{"Best" : 9, 'c' : 11}]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 'Best'
res = dict()
for sub in test_list:
# merging all Dictionaries into 1
res.update(sub)
# printing result
print("The extracted value : " + str(res[K]))
输出
The original list : [{'Gfg': 3, 'b': 7}, {'is': 5, 'a': 10}, {'Best': 9, 'c': 11}]
The extracted value : 9