-3
mylist = [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6}]

i want it as

myDict ={'a': 1, 'b': 2,'c': 3, 'd': 4,'e': 5, 'f': 6}
Marlon Abeykoon
  • 10,709
  • 4
  • 53
  • 72
Shivaraj Koti
  • 45
  • 1
  • 8

3 Answers3

4

You can make use of ChainMap.

from collections import ChainMap
myDict = dict(ChainMap(*mylist ))
wjandrea
  • 23,210
  • 7
  • 49
  • 68
Muhammad Tahir
  • 394
  • 1
  • 4
  • 7
0

This will take each dictionary and iterate through its key value pairs in for (k,v) in elem.items() part and assign them to a new dictionary.

mylist = [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6}]
new_dict = {k:v for elem in mylist for (k,v) in elem.items()}
print new_dict

This will replace the duplicated keys.

Marlon Abeykoon
  • 10,709
  • 4
  • 53
  • 72
0

I would create a new dictionary, iterate over the dictionaries in mylist, then iterate over the key/value pairs in that dictionary. From there, you can add each key/value pair to myDict.

mylist = [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6}]
myDict = {}

for Dict in mylist:
    for key in Dict:
        myDict[key] = Dict[key]

print(myDict)
John Luscombe
  • 163
  • 1
  • 8