来源:python中国网 时间:2020-03-14

  需求:

  两个字典dict1和dict2,要求合并,如果两个字典键相同则把值放在一个列表里,如果键不同则值单独保留为一个列表。(合并后的结果如下)[ps:python两个字典合并key相同时后面字典值会覆盖前面的字典]

  代码如下:


# -*- coding: utf-8 -*-
dict1 = {'aa':'1','bb':'2','dd':'2'}
dict2 = {'aa':'2','bb':'4','cc':'1'}
dict3 = {'aa':['1','2'],'bb':['2','4'],'cc':['1'],'dd':['2']}

dict1_item = (dict1.items())
dict2_item = (dict2.items())
dict3 = {}
for k1,v1 in dict1_item:
    for k2,v2 in dict2_item:
        if k1 == k2:
            dict3[k1] = [v1,v2]
    if k1 not in dict2:
        dict3[k1] = [v1]

for k2,v2 in dict2_item:
    if k2 not in dict1:
        dict3[k2] = [v2]
print(dict3)



D:python3installpython.exe D:/python/py3script/python66.py
{'aa': ['1', '2'], 'bb': ['2', '4'], 'dd': ['2'], 'cc': ['1']}

Process finished with exit code 0

每篇文章旨在解决一个问题,有帮助,赏瓶水。

疑难杂症

Tips:不要怕、多坚持、多动手、付出必有回报。