Python程序在字典列表中显示具有相同值的键
给定一个包含所有字典元素的列表,任务是编写一个Python程序来提取所有字典中具有相似值的键。
例子:
Input : test_list = [{“Gfg”: 5, “is” : 8, “best” : 0}, {“Gfg”: 5, “is” : 1, “best” : 0}, {“Gfg”: 5, “is” : 0, “best” : 0}]
Output : [‘Gfg’, ‘best’]
Explanation : All Gfg values are 5 and best has 0 as all its values in all dictionaries.
Input : test_list = [{“Gfg”: 5, “is” : 8, “best” : 1}, {“Gfg”: 5, “is” : 1, “best” : 0}, {“Gfg”: 5, “is” : 0, “best” : 0}]
Output : [‘Gfg’]
Explanation : All Gfg values are 5.
方法 1:使用keys()和循环
在这里,我们使用循环遍历列表中的所有元素,并使用 keys() 提取键。对于每个键,比较每个字典的键,如果发现相似,则将键添加到结果中。
Python3
# initializing Matrix
test_list = [{"Gfg": 5, "is": 8, "best": 0},
{"Gfg": 5, "is": 1, "best": 0},
{"Gfg": 5, "is": 0, "best": 0}]
# printing original list
print("The original list is : " + str(test_list))
# getting keys
keys = list(test_list[0].keys())
res = []
# iterating each dictionary for similar key's value
for key in keys:
flag = 1
for ele in test_list:
# checking for similar values
if test_list[0][key] != ele[key]:
flag = 0
break
if flag:
res.append(key)
# printing result
print("Similar values keys : " + str(res))
Python3
# initializing Matrix
test_list = [{"Gfg": 5, "is": 8, "best": 0},
{"Gfg": 5, "is": 1, "best": 0},
{"Gfg": 5, "is": 0, "best": 0}]
# printing original list
print("The original list is : " + str(test_list))
# getting keys
keys = list(test_list[0].keys())
res = []
# iterating each dictionary for similar key's value
for key in keys:
# using all to check all keys with similar values
flag = all(test_list[0][key] == ele[key] for ele in test_list)
if flag:
res.append(key)
# printing result
print("Similar values keys : " + str(res))
输出:
The original list is : [{‘Gfg’: 5, ‘is’: 8, ‘best’: 0}, {‘Gfg’: 5, ‘is’: 1, ‘best’: 0}, {‘Gfg’: 5, ‘is’: 0, ‘best’: 0}]
Similar values keys : [‘Gfg’, ‘best’]
方法 2:使用all() 、 loop和keys()
在这种情况下,内部循环被避免并替换为 all() ,它检查所有具有相似值的键,然后提取键。
蟒蛇3
# initializing Matrix
test_list = [{"Gfg": 5, "is": 8, "best": 0},
{"Gfg": 5, "is": 1, "best": 0},
{"Gfg": 5, "is": 0, "best": 0}]
# printing original list
print("The original list is : " + str(test_list))
# getting keys
keys = list(test_list[0].keys())
res = []
# iterating each dictionary for similar key's value
for key in keys:
# using all to check all keys with similar values
flag = all(test_list[0][key] == ele[key] for ele in test_list)
if flag:
res.append(key)
# printing result
print("Similar values keys : " + str(res))
输出:
The original list is : [{‘Gfg’: 5, ‘is’: 8, ‘best’: 0}, {‘Gfg’: 5, ‘is’: 1, ‘best’: 0}, {‘Gfg’: 5, ‘is’: 0, ‘best’: 0}]
Similar values keys : [‘Gfg’, ‘best’]