Skip to content
Advertisement

“Flattening” a list of dictionaries

So my aim is to go from:

fruitColourMapping = [{'apple': 'red'}, {'banana': 'yellow'}]

to

finalMap = {'apple': 'red', 'banana': 'yellow'}

A way I got is:

 from itertools import chain
 fruits = list(chain.from_iterable([d.keys() for d in fruitColourMapping]))
 colour = list(chain.from_iterable([d.values() for d in fruitColourMapping]))
 return dict(zip(fruits, colour))

Is there any better more pythonic way?

Advertisement

Answer

finalMap = {}
for d in fruitColourMapping:
    finalMap.update(d)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement