简体   繁体   English

仅在python中的两个字典中比较匹配键的值

[英]Only compare values of matching keys in two dictionaries in python

What is the most pythonic way of simply comparing: 简单比较的最Python方式是什么:

dict1 = {'Class1': 10, 'Class2': 18, 'Class3': 5}
dict2 = {'Class1': 10, 'Class2': 18, 'Class4': 11}

for key in dict1:
    for key2 in dict2:
        if key == key2:
            self.assertEqual(dict1[key], dict2[key2])

I feel like my solution of doing a nested for loop to compare all of dict2 keys to each key in dict1 is inefficient. 我觉得我做一个嵌套的for循环来比较所有dict2键和dict1中的每个键的解决方案效率低下。 The goal is to only compare the value for the keys that both dict1 and dict2 have. 目的是仅比较dict1和dict2都具有的键的值。

You can get the key intersection on which to iterate and compare with 您可以获得迭代和比较的关键交集

dict1.keys() & dict2.keys()

For instance, 例如,

>>> {k: (dict1[k], dict2[k]) for k in dict1.keys() & dict2.keys()}
{'Class1': (10, 10), 'Class2': (18, 18)}

# or 

>>> for k in dict1.keys() & dict2.keys():
        print(dict1[k], dict2[k])

18 18
10 10

Building on @Mitch's answer you can compare them inside all : 以@Mitch的答案为基础,您可以在all进行比较:

dict1 = {'Class1': 10, 'Class2': 18, 'Class3': 5}
dict2 = {'Class1': 10, 'Class2': 18, 'Class4': 11}
all(dict1[k] == dict2[k] for k in dict1.keys() & dict2.keys())

or in your case: 或者您的情况:

self.assertTrue(all(dict1[k] == dict2[k] for k in dict1.keys() & dict2.keys()))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM