在python字典中插入或更新键

lov*_*esh 8 python algorithm dictionary

我有一个dict1包含超过20,000个键的python字典,我希望update用另一个字典dict2.字典看起来像这样:

dict1
  key11=>[value11]
  key12=>[value12]
  ...
  ...
  keyxyz=>[value1x]      //common key
  ...... so on

dict2
  key21=>[value21]
  key22=>[value22]
  ...
  ...
  keyxyz=>[value2x]      // common key
  ........ so on
Run Code Online (Sandbox Code Playgroud)

如果我使用

dict1.update(dict2)
Run Code Online (Sandbox Code Playgroud)

然后其键dict1与键的类似dict2将使其值被值覆盖dict2.我想要的是如果一个键已经存在于dict1中,那么dict2中该键的值应该附加到dict1的值.所以

dict1.conditionalUpdate(dict2)
Run Code Online (Sandbox Code Playgroud)

应该导致

dict1
  key11=>[value11]
  key12=>[value12]
  key21=>[value21]
  key22=>[value22]
  ...
  ...
  keyxyz=>[value1x,value2x]
Run Code Online (Sandbox Code Playgroud)

一种天真的方法是迭代dict2每个键的键dict1并插入或更新键.有更好的方法吗?python是否支持支持这种功能的内置数据结构?

Bur*_*lid 8

使用defaultdict集合模块.

>>> from collections import defaultdict
>>> dict1 = {1:'a',2:'b',3:'c'}
>>> dict2 = {1:'hello', 4:'four', 5:'five'}
>>> my_dict = defaultdict(list)
>>> for k in dict1:
...    my_dict[k].append(dict1[k])
...
>>> for k in dict2:
...    my_dict[k].append(dict2[k])
...
>>> my_dict[1]
['a', 'hello']
Run Code Online (Sandbox Code Playgroud)