Python两个字典的合并

两个字典合并的,有几种方法

1
2
3
4
dict1={1:[1,11,111],2:[2,22,222]}
dict2={3:[3,33,333],4:[4,44,444]}
#得到如下的结果
{1:[1,11,111],2:[2,22,222],3:[3,33,333],4:[4,44,444]}

两个方法:

  1. dictMerged=dict(dict1.items()+dict2.items())

  2. dictMerged2=dict(dict1, **dict2)

    其中方法2类似于:

    dictMerged=dict1.copy()
    dictMerged.update(dict2)

但是如果两个字典中有相同的key怎么办?

如下:

1
2
a = dict(a=1, b=None, c=3)
b = dict(a=None, b=2, c=4)

要合并这两个字典该怎么办?

1
2
3
4
for k, v in b.items():
if v:
a[k] = v
print a

Comments

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×