通过添加值而不是替换它来更新一个字典与另一个字典

时间:2011-08-26 14:56:05

标签: python dictionary

我有很多这样的词典:

dict1 = {1:[1,2,3],2:[2,3,4]}
dict2 = {2:[3,4,5],3:[4,5,6]}

我需要

dict = {1:[1,2,3],2:[2,3,4,3,4,5],3:[4,5,6]}
#                       ^
#                       | order is unimportant

这样做的最佳方式是什么?

6 个答案:

答案 0 :(得分:6)

简单迭代扩展列表......

for key, value in dict2.iteritems():
    dict1.setdefault(key, []).extend(value)

答案 1 :(得分:1)

dict1 = {1:[1,2,3],2:[2,3,4]}
dict2 = {2:[3,4,5],3:[4,5,6]}

dicts = [dict1, dict2]
new_dict = {}

for d in dicts:
  for k, v in d.iteritems():
    if new_dict.has_key(k):
      new_dict[k] = new_dict[k] + v
    else:
      new_dict[k] = v

答案 2 :(得分:0)

迭代dict2的键;如果dict1中存在相同的密钥,则连接列表并在dict1中设置;否则只需在dict1中设置

答案 3 :(得分:0)

a = {'a' : [1,2], 'b' : [3,4]}
b = {'a' : [3,4], 'b' : [1,2]}

for key in a.keys():
    for elem in a[key]:
        b[key].append(elem)

答案 4 :(得分:0)

哦,也许有一些聪明的方法可以用reduce来做,但为什么不像普通人一样编写代码。

dict = {}
for each_dict in (dict1, dict2, ...): # ... is not real code
    for key, value in each_dict:
        if not dict.has_key(key):
            dict[key] = []
        dict[key] += value # list append operator

答案 5 :(得分:0)

  

我有很多这样的词典:

通过这种方式,您可以一次“粘合”多个词典:

dict(
  (k, sum((d.get(k, []) for d in dicts), []))
  for k in set(sum((d.keys() for d in dicts), []))
)