📜  Python – 与字典中的多个相似值配对

📅  最后修改于: 2022-05-13 01:55:44.933000             🧑  作者: Mango

Python – 与字典中的多个相似值配对

有时,在使用字典时,我们可能会遇到一个问题,即我们需要将具有相似键值的字典保留在其他字典中。这是一个非常具体的问题。这可以在 Web 开发领域有应用。让我们讨论可以执行此任务的某些方式。

方法#1:使用列表推导
可以使用列表推导来执行此任务。在此我们迭代列表中的每个元素并运行嵌套循环以将键的值与其他所有值匹配。

# Python3 code to demonstrate 
# Pairs with multiple similar values in dictionary
# using list comprehension
  
# Initializing list
test_list = [{'Gfg' : 1, 'is' : 2}, {'Gfg' : 2, 'is' : 2}, {'Gfg' : 1, 'is' : 2}]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Pairs with multiple similar values in dictionary
# using list comprehension
res = [sub for sub in test_list if len([ele for ele in test_list if ele['Gfg'] == sub['Gfg']]) > 1]
  
# printing result 
print ("List after keeping dictionary with same key's value : " + str(res))
输出 :
The original list is : [{'is': 2, 'Gfg': 1}, {'is': 2, 'Gfg': 2}, {'is': 2, 'Gfg': 1}]
List after keeping dictionary with same key's value : [{'is': 2, 'Gfg': 1}, {'is': 2, 'Gfg': 1}]

方法 #2:使用Counter() + 列表推导
在此方法中,使用 Counter() 执行查找频率的任务,然后使用列表推导完成查找具有多个键值的元素的任务。

# Python3 code to demonstrate 
# Pairs with multiple similar values in dictionary
# using list comprehension + Counter()
from collections import Counter
  
# Initializing list
test_list = [{'Gfg' : 1, 'is' : 2}, {'Gfg' : 2, 'is' : 2}, {'Gfg' : 1, 'is' : 2}]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Pairs with multiple similar values in dictionary
# using list comprehension + Counter()
temp = Counter(sub['Gfg'] for sub in test_list)
res = [ele for ele in test_list if temp[ele['Gfg']] > 1]
  
# printing result 
print ("List after keeping dictionary with same key's value : " + str(res))
输出 :
The original list is : [{'is': 2, 'Gfg': 1}, {'is': 2, 'Gfg': 2}, {'is': 2, 'Gfg': 1}]
List after keeping dictionary with same key's value : [{'is': 2, 'Gfg': 1}, {'is': 2, 'Gfg': 1}]