如何判断python两个字典里面相同key对应的值是不是相等?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何判断python两个字典里面相同key对应的值是不是相等?相关的知识,希望对你有一定的参考价值。
a = 10000: 3, 10001: 100, 10002: 7, 10003: 2000, 10004: 19
c = 10000: 3, 10001: 100, 10002: 7, 10003: 200, 10004: 19, 10005: 9, 10006: 10, 10007: 17, 10008: 82, 10009: 3, 10010: 23, 10011: 11
如何判断a里面key的值和c里面相同key对应的值是否相等?
if key in c:
if c[key] == a[key]:
print('key %s 相等' % key)
else:
print('key %s 不相等' % key)
else:
print('c中无key %s' % key)本回答被提问者采纳
Python两个字典key相同的值组成新字典?
dic1='福州龙湖': ['1293521.23', '620624'], '赣州龙湖': ['3050.51']
dic2='福州龙湖': ['12345', '67890'], '赣州龙湖': ['123','456']
想组成:dic3='福州龙湖': [['1293521.23', '620624'],['12345', '67890']], '赣州龙湖': [['3050.51'],['123','456']]可否实现?
按照你的要求编写的两个字典key相同的值组成新字典的Python程序如下
dic1='福州龙湖': ['1293521.23', '620624'], '赣州龙湖': ['3050.51']
dic2='福州龙湖': ['12345', '67890'], '赣州龙湖': ['123','456']
dic3=
for key in dic1:
if dic2.get(key):
dic3[key]=[dic1[key],dic2[key]]
else:
dic3[key]=dic1[key]
for key in dic2:
if dic1.get(key):
pass
else:
dic3[key]=dic2[key]
print(dic3)
源代码(注意源代码的缩进)
运行结果
'福州龙湖': [['1293521.23', '620624'], ['12345', '67890']], '赣州龙湖': [['3050.51'], ['123', '456']]
追问您好还有个问题如果我是多个字典组成呢?
按照你的要求编写的多个字典key相同的值组成新字典的Python程序如下
def hebing(dic1,dic3):
for key in dic1:
if dic3.get(key):
dic3[key].append(dic1[key])
else:
dic3[key]=[dic1[key]]
return dic3
dic1='福州龙湖': ['1293521.23', '620624'], '赣州龙湖': ['3050.51']
dic2='福州龙湖': ['12345', '67890'], '赣州龙湖': ['123','456']
dic4='福州龙湖': ['789', '888'], '北京龙湖': ['111']
dic3=
dic3=hebing(dic1,dic3)
dic3=hebing(dic2,dic3)
dic3=hebing(dic4,dic3)
print(dic3)
源代码(注意源代码的缩进)
运行结果
'福州龙湖': [['1293521.23', '620624'], ['12345', '67890'], ['12345', '67890']], '赣州龙湖': [['3050.51'], ['123', '456']], '北京龙湖':[['111']]
默认的字典更新是同key覆盖
所以
以上是关于如何判断python两个字典里面相同key对应的值是不是相等?的主要内容,如果未能解决你的问题,请参考以下文章
Python 如果两个字典key值相同,如何提取对应values组成新的字典