简体   繁体   English

比较两个字典的值

[英]Comparing values of two dictionaries

I have two dictionaries as follows: 我有两个字典,如下所示:

a = {1:2, 3:4, 5:6}
b = {1:5, 3:6, 7:1}

For every key in a , I want to check if the key exists in b , if so, I want to print the value of both keys, if it does not, I print 0 as the value of the key in b : 对于每一个键a ,我要检查钥匙存在b ,如果是的话,我要同时打印键的值,如果没有,我打印0作为键的值b

for key in a.keys():
    if key in b.keys():
        print key, a[key], b[key]
    else:
        print key, a[key], '0'

The output would be: 输出为:

1 2 5
3 4 6
5 6 0

But, I also want to print the value of key in b if it does not exist in a , that is the opposite of the last statement, if key is in b but not in a , print the value of the key in b and 0 as the value of the key in a . 但是,我也想打印键的值b ,如果它不存在a ,那就是最后的陈述相反,如果关键是在b而不是在a ,打印键的值b0作为键的值a The output would be: 输出为:

1 2 5
3 4 6
5 6 0
7 0 1

It should be simple but I can't figure out how I can do it. 它应该很简单,但是我不知道该怎么做。 Thanks! 谢谢!

If I understand correctly, you want to iterate through all keys from either dictionary, and print their values from the two dictionaries, using '0' if the key is missing from that dictionary. 如果我理解正确,那么您要遍历任一词典中的所有键,并从两个词典中打印它们的值,如果该词典中缺少键,请使用'0' Something like this: 像这样:

for key in set(a)|set(b):
    print key, a.get(key, '0'), b.get(key, '0')

set(a)|set(b) is the union of the sets of keys from each dictionary (ie it is a collection of distinct keys from either dictionary). set(a)|set(b)是每个字典的键集的并集(即,这是来自每个字典的不同键的集合)。

dictionary.get(key, '0') returns '0' if the key is missing from the dictionary. 如果字典中缺少dictionary.get(key, '0')返回'0'

for key in set(a.keys()) | set(b.keys()):
    print key, a.get(key, 0), b.get(key,0)

| means union in a set context. 表示在特定上下文中的并集。 You can also convert the resulting set into a list and sort it before iterating. 您还可以将结果集转换为列表并在迭代之前对其进行排序。

Use dict b 's get method, supplying a default value for use when the key isn't found. 使用dict bget方法,提供默认值以在找不到密钥时使用。

for key in a:
    print key, a[key], b.get(key, '0')

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

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