Python两个字典key相同的值组成新字典?
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']]}