Python - 两个字典的键之间的差异
pythonserver side programmingprogramming更新于 2025/9/7 14:04:17
两个 Python 字典之间可能包含一些共同的键。在本文中,我们将了解如何获取两个给定字典中存在的键之间的差异。
使用 set
这里我们取两个字典并对它们应用 set 函数。然后我们将这两个集合相减以获得差异。我们以两种方式进行,从第一个字典中减去第二个字典,然后从第二个字典中减去第一个字典。不常见的键列在结果集中。
示例
dictA = {'1': 'Mon', '2': 'Tue', '3': 'Wed'}
print("1st Distionary:\n",dictA)
dictB = {'3': 'Wed', '4': 'Thu','5':'Fri'}
print("1st Distionary:\n",dictB)
res1 = set(dictA) - set(dictB)
res2 = set(dictB) - set(dictA)
print("\nThe difference in keys between both the dictionaries:")
print(res1,res2)
输出
运行上述代码得到以下结果 −
1st Distionary:
{'1': 'Mon', '2': 'Tue', '3': 'Wed'}
1st Distionary:
{'3': 'Wed', '4': 'Thu', '5': 'Fri'}
The difference in keys between both the dictionaries:
{'2', '1'} {'4', '5'}
在 for 循环中使用 in
在另一种方法中,我们可以使用 for 循环遍历一个字典的键,并使用第二个字典中的 in 子句检查其是否存在。
示例
dictA = {'1': 'Mon', '2': 'Tue', '3': 'Wed'}
print("1st Distionary:\n",dictA)
dictB = {'3': 'Wed', '4': 'Thu','5':'Fri'}
print("1st Distionary:\n",dictB)
print("\nThe keys in 1st dictionary but not in the second:")
for key in dictA.keys():
if not key in dictB:
print(key)
输出
运行上述代码得到以下结果 −
1st Distionary:
{'1': 'Mon', '2': 'Tue', '3': 'Wed'}
1st Distionary:
{'3': 'Wed', '4': 'Thu', '5': 'Fri'}
The keys in 1st dictionary but not in the second:
1
2
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

