Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"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?

like image 388
user1741339 Avatar asked Sep 06 '25 03:09

user1741339


1 Answers

Why copy at all?

In Python 3, you can use the new ChainMap:

A ChainMap groups multiple dicts (or other mappings) together to create a single, updateable view.
The underlying mappings are stored in a list. That list is public and can accessed or updated using the maps attribute. There is no other state. Lookups search the underlying mappings successively until a key is found. In contrast, writes, updates, and deletions only operate on the first mapping.

All you need is this (do change the names to abide by Python naming conventions):

from collections import ChainMap
fruit_colour_mapping = [{'apple': 'red'}, {'banana': 'yellow'}]
final_map = ChainMap(*fruit_colour_mapping)

And then you can use all the normal mapping operations:

# print key value pairs:
for element in final_map.items():
    print(element)

# change a value:
final_map['banana'] = 'green'    # supermarkets these days....

# access by key:
print(final_map['banana'])
like image 135
Adam Avatar answered Sep 07 '25 19:09

Adam