28

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?

3
  • FYI, you really don't want to do it this way. Dictionaries are intrinsically unordered, so it is only a matter of luck that iterating over the dictionary twice (as you do to build the fruit and color lists) generates 2 sets of values in the correct order.
    – Silas Ray
    Mar 26, 2013 at 21:55
  • 5
    @sr2222 not true. The documentation explicitly states that if you iterate over keys and values without mutating the dictionary in the meantime, the order is guaranteed to correspond. Mar 26, 2013 at 22:02
  • 1
    @DanielRoseman It's still not a good habit to get in to though. It won't be thread safe if that ever becomes a concern, and just because something implements the same interface as a dictionary doesn't mean it will behave exactly like a dictionary in these sorts of details. It's the kind of thing that works fine until it doesn't, and then you get subtle hard to track down bugs. It's easy enough to avoid, so you might as well do so.
    – Silas Ray
    Mar 27, 2013 at 13:31

9 Answers 9

41

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'])
2
  • 1
    +1 I think this is one of the cooler dict additions in python 3. First saw this in the new Python Cookbook.
    – hughdbrown
    Jun 18, 2013 at 20:24
  • search operation of ChainMap is much slower than Python dictionary. You should convert to final_map to a Python dictionary.
    – haluk
    Feb 11, 2018 at 5:24
35
{k: v for d in fruitColourMapping for k, v in d.items()}
32
finalMap = {}
for d in fruitColourMapping:
    finalMap.update(d)
3
  • Just curious: should it work if one of 'd's is {'apple': 'red', 'orange': 'orange'}? Mar 26, 2013 at 22:00
  • This code will simply add all dictionary entries to finalMap, so it will add both apple and orange keys.
    – nneonneo
    Mar 26, 2013 at 22:01
  • And when moving beyond simple examples, make sure all the keys are globally unique because update (or any method that ends with a single dict) will deduplicate the keys. If you need all the duplicates (e.g. when all dicts have the same keys), convert the dicts to pandas DataFrames before concatenating.
    – mirekphd
    Jun 27, 2020 at 14:07
14

Rather than deconstructing and reconstructing, just copy and update:

final_map = {}
for fruit_color_definition in fruit_color_mapping:
    final_map.update(fruit_color_definition)
6
dict(d.items()[0] for d in fruitColourMapping)
6

Approach

Use reduce to apply each dict to an empty initializer. Since dict.update always returns None, use d.update(src) or d to give reduce the desired return value.

Code

final_dict = reduce(lambda d, src: d.update(src) or d, dicts, {})

Test

>>> dicts = [{'a': 1, 'b': 2}, {'b': 3, 'c': 4}, {'a': 6}]
>>> final_dict = reduce(lambda d, src: d.update(src) or d, dicts, {})
>>> final_dict
{'a': 6, 'c': 4, 'b': 3}
3
  • 1
    In order to feel a less hacky, you might consider using the new dict merging syntax with the overload of the OR operator: final_dict = reduce(lambda x, y: x | y, dicts, {})
    – Nei Neto
    Dec 15, 2021 at 3:51
  • @NeiNeto your comment is anachronistic. When I wrote this in 2013, the latest python was 3.3.0. The feature you suggest I ought to have written about would not exist for several more years.
    – hughdbrown
    Dec 16, 2021 at 19:20
  • Indeed. Quite the bruh moment. Fortunately for the achronicity of my comment, the "you" I'm referring to is the reader rather than you, Hugh. Btw, nice word of the day that one, felt like something straight from vsauce. Would you consider editing your answer, though?
    – Nei Neto
    Dec 18, 2021 at 1:15
5

Given

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

Code

In Python 3.5, dictionary unpacking was introduced (see PEP 448):

{**d1, **d2}
# {'apple': 'red', 'banana': 'yellow'}

In Python 3.9, the merge operator was introduced:

d1 | d2
# {'apple': 'red', 'banana': 'yellow'}
4

I came up with a interesting one liner.

>>> a = [{"wow": 1}, {"ok": 2}, {"yeah": 3}, {"ok": [1,2,3], "yeah": True}]
>>> a = dict(sum(map(list, map(dict.items, a)), []))
>>> a
{'wow': 1, 'ok': [1, 2, 3], 'yeah': True}
2

You could also try:

finalMap = dict(item for mapping in fruitColourMapping for item in mapping.items())

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.