Python两个字典key相同的值组成新字典?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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计算两个字典的相同点(从keyvalueitem角度)
如何判断python两个字典里面相同key对应的值是不是相等?