可以使用Python的内置函数dict.items()
来比较两个字典是否相同,并打印出不匹配的键和值。
下面是一个示例代码:
dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'a': 1, 'b': 4, 'd': 5}
# 比较两个字典是否相同
if dict1 == dict2:
print("两个字典相同")
else:
print("两个字典不同")
# 打印出不匹配的键和值
for key, value in dict1.items():
if key not in dict2 or dict2[key] != value:
print("键: %s, 字典1的值: %s, 字典2的值: %s" % (key, value, dict2.get(key)))
for key, value in dict2.items():
if key not in dict1 or dict1[key] != value:
print("键: %s, 字典1的值: %s, 字典2的值: %s" % (key, dict1.get(key), value))
上述代码首先比较两个字典是否相同,如果相同则打印出"两个字典相同",否则打印出"两个字典不同"。
接着,使用dict.items()
遍历字典1的键值对,检查每个键是否存在于字典2中,如果不存在,则打印出不匹配的键和值。然后,再次使用dict.items()
遍历字典2的键值对,检查每个键是否存在于字典1中,如果不存在,则打印出不匹配的键和值。
运行上述代码,将输出:
两个字典不同
键: b, 字典1的值: 2, 字典2的值: 4
键: c, 字典1的值: 3, 字典2的值: None
键: d, 字典1的值: None, 字典2的值: 5
其中,键'b'的值在字典1中为2,在字典2中为4;键'c'只存在于字典1中,值为3,而字典2中不存在;键'd'只存在于字典2中,值为5,而字典1中不存在。