-3

I have a list of Python dictionaries with the same keys. I would like to create a big dictionary from the ones in the list. The thing is I cannot use update to create a new one because, as the keys are the same, the value for each key is overwritten in the process. A sample of my list is:

[{0: u'ChIJIxtmpVdCQg0R_TCH5ttvqC0',
  1: u'ChIJ2RMaMThvQg0R_6hmMXFiG_M',
  ...
  195: u'ChIJv1KfnmMpQg0R5iC9EmaXN6M',
  196: u'ChIJd0vQCiOEQQ0RasOKsxksdys'},
 {0: u'ChIJIxtmpVdCQg0R_TCH5ttvqC0',
  1: u'ChIJ2RMaMThvQg0R_6hmMXFiG_M',
  2: u'ChIJQ3PGOWlfQg0RkV-a6JQdrFs',
  3: u'ChIJ-TjccjhvQg0RVQmnPNgAJv4',
  ...
  100: u'ChIJN7zqEhgmQg0R-NzvqSYG_Ds',
  101: u'ChIJPTR-xaYoQg0RUrX7K8kQhU4',
  102: u'ChIJV_pHsIsoQg0ReGKLBXDqOc8',
  103: u'ChIJtXpyqps7Qg0RXq37551oP4o',...

What I want is a bigger dictionary of the following form:

{0: u'ChIJIxtmpVdCQg0R_TCH5ttvqC0',
  1: u'ChIJ2RMaMThvQg0R_6hmMXFiG_M',
  2: u'ChIJQ3PGOWlfQg0RkV-a6JQdrFs',
  3: u'ChIJ-TjccjhvQg0RVQmnPNgAJv4',
  ...
  195: u'ChIJv1KfnmMpQg0R5iC9EmaXN6M',
  196: u'ChIJd0vQCiOEQQ0RasOKsxksdys', ###HERE STARTS THE NEW DICT!!
  197: u'ChIJIxtmpVdCQg0R_TCH5ttvqC0',
  198: u'ChIJ2RMaMThvQg0R_6hmMXFiG_M',
  199: u'ChIJQ3PGOWlfQg0RkV-a6JQdrFs',
  ...

Where the keys increase up to the number of instances among all the dictionaries.

Thanks in advance.

Gonzalo Donoso
  • 657
  • 1
  • 6
  • 17

4 Answers4

1

Try something like this:

vals = []
for d in list_of_dicts:
   vals.extend(d.values())

max_dict = dict(enumerate(vals))
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
1

You could simply retreive the current size of the dictionary as key for each element.

myDict = {}
for dictionary in dictionaries:
  for key in dictionary:
    myDict[len(myDict)] = dictionary[key]
yanneke
  • 106
  • 7
0

If, as you say, the keys are sort of ids in the sense that they are consecutive integers, and you want to sort of append the values in the second dict, i.e. forget their original keys, then this could work:

dict(enumerate(list(dict1.values()) + list(dict2.values())))

If you have more than two source dictionaries, a little extra magic is necessary:

dict(enumerate([item for sublist in [list(d.values()) for d in dicts] for item in sublist]))

(The outer list comprehension is copied from the accepted answer to this question: Making a flat list out of list of lists in Python)

steffen
  • 8,572
  • 11
  • 52
  • 90
0

To merge dict2 into dict1 this should work

dict1 = {1: 'a', 2: 'b'}
dict2 = {1: 'c', 2: 'd'}

max_key_in_dict1 = max(dict1.keys())
for key in dict2.keys():
    dict1[key+max_key_in_dict1] = dict2[key]
del dict2

dict1 is then:

{1: 'a', 2: 'b', 3: 'c', 4: 'd'}
commoner
  • 51
  • 2