1

I have many dictionaries like this:

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

I need to get

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

What is the best way of doing it?

Morse
  • 1,330
  • 2
  • 17
  • 27

6 Answers6

7

Simple iteration an extending list...

for key, value in dict2.iteritems():
    dict1.setdefault(key, []).extend(value)
JC Plessis
  • 683
  • 3
  • 7
1

Iterate through the keys of dict2; if the same key exists in dict1, concatenate the lists and set in dict1; otherwise just set in dict1

antlersoft
  • 14,636
  • 4
  • 35
  • 55
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
Martin
  • 5,954
  • 5
  • 30
  • 46
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)
Thomas Dignan
  • 7,052
  • 3
  • 40
  • 48
0

Oh, maybe there's some clever way to do it with reduce, but why not just write code like a normal person.

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
morningstar
  • 8,952
  • 6
  • 31
  • 42
0

I have many dictionaries like this:

This way lets you "glue together" multiple dictionaries at a time:

dict(
  (k, sum((d.get(k, []) for d in dicts), []))
  for k in set(sum((d.keys() for d in dicts), []))
)
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153