python中的字典的键_Python-两个字典键的区别

本文介绍了如何找出两个Python字典之间的键的差异。通过将字典转换为集合并应用集合的差集操作,我们可以轻松获取不共有的键。示例展示了两种方法:一是从第一个字典减去第二个字典,二是反之。此外,还提供了使用for循环检查键是否存在于另一个字典中的方法。
摘要由CSDN通过智能技术生成

两个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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值