📜  Python – 常用项字典值列表

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

Python – 常用项字典值列表

union 的功能已经讨论过很多次了。但有时,我们可以有一个更复杂的容器,我们需要在其中检查以字典键形式存在的列表的交集。让我们讨论解决此类问题的某些方法。

方法#1:使用循环
使用循环是执行此特定任务的一种天真的蛮力方法。在这种方法中,我们检查两个列表中都存在的键。我们甚至检查其他完全不存在的键以添加其整个列表值。

# Python3 code to demonstrate
# Common elements Dictionary Value List
# using loops
  
# initializing dicts
test_dict1 = { "Key1" : [1, 3, 4], "key2" : [4, 5] }
test_dict2 = { "Key1" : [1, 7, 3] }
  
# printing original dicts
print("The original dict 1 : " + str(test_dict1))
print("The original dict 2 : " + str(test_dict2))
  
# using loops
# Common elements Dictionary Value List
res = dict()
for key in test_dict1: 
    if key in test_dict2: 
        res[key] = []
        for val in test_dict1[key]:
            if val in test_dict2[key]:
                res[key].append(val)
  
# print result
print("The dicts after intersection is : " + str(res))
输出 :
The original dict 1 : {'Key1': [1, 3, 4], 'key2': [4, 5]}
The original dict 2 : {'Key1': [1, 7, 3]}
The dicts after intersection is : {'Key1': [1, 3]}

方法#2:使用字典理解+集合操作
这是解决类似问题的单线方法,并为上述方法提供了一种紧凑的替代方案。此解决方案通过使用集合推导来处理,以使用字典推导将必要的元素绑定到列表中。

# Python3 code to demonstrate
# Common elements Dictionary Value List
# using dictionary comprehension + set operations
  
# initializing dicts
test_dict1 = { "Key1" : [1, 3, 4], "key2" : [4, 5] }
test_dict2 = { "Key1" : [1, 7, 3] }
  
# printing original dicts
print("The original dict 1 : " + str(test_dict1))
print("The original dict 2 : " + str(test_dict2))
  
# using dictionary comprehension + set operations
# Common elements Dictionary Value List
res = {key : list(set(set(test_dict1.get(key, [])) & set(test_dict2.get(key, [])))) 
    for key in set(test_dict2) & set(test_dict1)}
  
# print result
print("The dicts after intersection is : " + str(res))
输出 :
The original dict 1 : {'Key1': [1, 3, 4], 'key2': [4, 5]}
The original dict 2 : {'Key1': [1, 7, 3]}
The dicts after intersection is : {'Key1': [1, 3]}