python - 比较两个字典并在 python 中打印不相等的值

标签 python dictionary key inequality

我需要比较字典 b 和 a 来检查 b 的键是否在 a 中。

如果存在,检查 a[key]==b[key] 的值。如果不相等,打印两个字典的 key:value 对以供引用。我该怎么做?

a = {'key_1': 1,'key_2': 2, 'key_3': 3}
b = {'key_1': 1,'key_2': 5}

[k for key in b if key in a if b[k]!=a[k]]

我使用了上面的代码,但无法同时打印字典键和值

not equal: b[key_2]=5 and a[key_2]=2

最佳答案

我需要将字典 b 与 a 进行比较,以检查 b 的键是否在 a 中。您想找到相交 键,然后检查它们的值:

a = {'key_1': 1,'key_2': 2, 'key_3': 3}
b = {'key_1': 1,'key_2': 5}

# find keys common to both
inter = a.keys() & b 
diff_vals = [(k, a[k], b[k]) for k in inter if a[k] != b[k]]
# find keys common to both
inter = a.keys() & b

for k,av, bv in diff_vals:
    print("key = {}, val_a = {}, val_b = {}".format(k, av, bv))
key = key_2, val_a = 2, val_b = 5

您可以在 dict_view 对象上使用许多不同的设置方法:

# find key/value pairings that are unique to either dict
symmetric = a.items() ^ b.items()
{('key_2', 2), ('key_2', 5), ('key_3', 3)}


# key/values in b that are not in a    
difference = b.items() - a.items()
{('key_2', 5)}

# key/values in a that are not in b
difference = a.items() - b.items()
{('key_3', 3), ('key_2', 2)}

# get unique set of all keys from a and b
union = a.keys() | b
{'key_1', 'key_2', 'key_3'}

# get keys common to both dicts
inter = a.keys() & b
{'key_1', 'key_2'}

关于python - 比较两个字典并在 python 中打印不相等的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40213268/

相关文章:

python - 如何在pyspark中将DataFrame转换回正常的RDD?

java - Java程序如何实现按键控制?

random - 如何在Perl 6中获得随机选择的哈希键?

python - 每次使用 python 运行脚本时,如何使用 while 循环并增加列表变量?

python结构解压长度错误

JavaScript - Map() 增量值

python - 如何使用索引根据键和值将字典拆分为多个字典?

JAVA:字符串问题的 128 位 key 和返回

Python 和 MySQL 连接器 : AttributeError: 'CMySQLCursor' object has no attribute 'next'

list - 如何将列表与特定键/值作为主机变量进行组合/匹配