0
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}
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Shivaraj Koti
  • 75
  • 1
  • 8
  • Start with checking [this question](https://stackoverflow.com/questions/41521431/python-flatten-a-list-of-objects) out, and then ask specifically where you're stuck. – vahdet Jul 03 '18 at 08:24
  • i have edited the question.now its is very clear to understand. – Shivaraj Koti Jul 03 '18 at 08:29

3 Answers3

6

You can make use of ChainMap.

from collections import ChainMap
myDict = dict(ChainMap(*mylist))
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Muhammad Tahir
  • 434
  • 1
  • 6
  • 7
  • ChainMap is better because it skips most of the work you'd have to do to construct a new dict and copy all the values. But if you force it to do that anyway, maybe just make an update loop? Can OP use the ChainMap directly instead of forcing it to a dict? – Kenny Ostrom Aug 18 '23 at 15:04
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
  • 11,927
  • 4
  • 54
  • 75
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
  • 343
  • 2
  • 9