来源:python中国网 时间:2019-07-17

  需求:

  两个字典dict1和dict2,要求合并,如果两个字典键相同则把值放在一个列表里,如果键不同则值单独保留为一个列表。

  代码如下:


# -*- 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