我有一个包含超过20,000个密钥的python字典dict1
,我希望update
使用另一个字典dict2
。字典看起来像这样:
dict1
key11=>[value11]
key12=>[value12]
...
...
keyxyz=>[value1x] //common key
...... so on
dict2
key21=>[value21]
key22=>[value22]
...
...
keyxyz=>[value2x] // common key
........ so on
如果我使用
dict1.update(dict2)
然后dict1
的键与dict2
的键类似,其值将被dict2
的值覆盖。我想要的是如果一个键已经存在于dict1中,那么dict2中该键的值应该附加到dict1的值。所以
dict1.conditionalUpdate(dict2)
应该导致
dict1
key11=>[value11]
key12=>[value12]
key21=>[value21]
key22=>[value22]
...
...
keyxyz=>[value1x,value2x]
一个天真的方法是为dict2
的每个键迭代dict1
的键并插入或更新键。有更好的方法吗? python是否支持支持这种功能的内置数据结构?
答案 0 :(得分:9)
使用集合模块中的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']
答案 1 :(得分:1)
使用dict理解和itertools.groupby()
实际上很简单:
dict1 = {1: 1, 2: 2, 3: 3, 4: 4}
dict2 = {5: 6, 7: 8, 1: 1, 2: 2}
from itertools import groupby, chain
from operator import itemgetter
sorted_items = sorted(chain(dict1.items(), dict2.items()))
print({key: [value[1] for value in values] for key, values in groupby(sorted_items, itemgetter(0))})
给我们:
{1: [1, 1], 2: [2, 2], 3: [3], 4: [4], 5: [6], 7: [8]}
当然,这会创建一个新的dict,但是如果你需要来更新第一个dict,你可以通过更新新的dict来轻松地做到这一点。如果你的值已经是列表,这可能需要一些小修改(但我认为你是为了操作而这样做的,在这种情况下,没有必要)。
当然,如果您使用的是Python 2.x,那么您需要使用dict.viewitems()
或dict.iteritems()
而不是dict.items()
。如果您在dict理解之前使用的是Python版本,那么您可以使用dict((key , value) for ...)
代替。
答案 2 :(得分:0)
另一种没有导入任何东西的方法,只需使用常规的Python字典:
>>> dict1 = {1:'a',2:'b',3:'c'}
>>> dict2 = {1:'hello', 4:'four', 5:'five'}
>>> for k in dict2:
... dict1[k] = dict1.get(k,"") + dict2.get(k)
...
>>> dict1
{1: 'ahello', 2: 'b', 3: 'c', 4: 'four', 5: 'five'}
>>>
dict1.get(k,"")
返回与k
相关联的值(如果存在)或否则返回空字符串,然后附加dict2
的内容。