Python - 两个字典中键值的差异
两个 Python 字典在它们之间可能有一些公共键。在本文中,我们将研究如何获得两个给定字典中的键的差异。
用集合
这里我们取两个字典并对其应用集合函数。然后我们减去两个集合以得出差异。我们通过两种方式执行此操作,通过从第一个字典中减去第二个字典,然后从第二个字典中减去第一个字典。结果集会列出那些非公共的键。
示例
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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP