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循环中使用
在另一种方法中,我们可以使用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热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿