Skip to main content
 首页 » 编程设计

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

2024年10月17日9yxwkf

我需要比较字典 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'}