user4602735
user4602735

Reputation:

How to combine a list of dictionaries to one dictionary

I have a list of dicts:

d =[{'a': 4}, {'b': 20}, {'c': 5}, {'d': 3}]

I want to remove the curly braces and convert d to a single dict which looks like:

d ={'a': 4, 'b': 20, 'c': 5, 'd': 3}

Upvotes: 2

Views: 9057

Answers (4)

Martijn Pieters
Martijn Pieters

Reputation: 1121476

If you don't mind duplicate keys replacing earlier keys you can use:

from functools import reduce  # Python 3 compatibility 
d = reduce(lambda a, b: dict(a, **b), d)

This merges the first two dictionaries then merges each following dictionary into the result built so far.

Demo:

>>> d =[{'a': 4}, {'b': 20}, {'c': 5}, {'d': 3}]
>>> reduce(lambda a, b: dict(a, **b), d)
{'a': 4, 'c': 5, 'b': 20, 'd': 3}

Or if you need this to work for arbitrary (non string) keys (and you are using Python 3.5 or greater):

>>> d =[{4: 4}, {20: 20}, {5: 5}, {3: 3}]
>>> reduce(lambda a, b: dict(a, **b), d) # This wont work
TypeError: keywords must be strings
>>> reduce(lambda a, b: {**a, **b}, d) # Use this instead
{4: 4, 20: 20, 5: 5, 3: 3}

The first solution hacks the behaviour of keyword arguments to the dict function. The second solution is using the more general ** operator introduced in Python 3.5.

Upvotes: 7

Nihal Sharma
Nihal Sharma

Reputation: 2437

a = [{'a': 4}, {'b': 20}, {'c': 5}, {'d': 3}]
b = {}
[b.update(c) for c in a]

b = {'a': 4, 'b': 20, 'c': 5, 'd': 3}

if order is important:

from collections import OrderedDict
a = [{'a': 4}, {'b': 20}, {'c': 5}, {'d': 3}]
newD = OrderedDict()
[newD.update(c) for c in a]
out = dict(newD)

Upvotes: 0

Pynchia
Pynchia

Reputation: 11580

Overwriting the values of existing keys, a brutal and inexperienced solution is

nd = {}
for el in d:
    for k,v in el.items():
    nd[k] = v

or, written as a dictionary comprehension:

d = {k:v for el in d for k,v in el.items()}

Upvotes: 1

elegent
elegent

Reputation: 4007

You just need to iterate over d and append (update()) the element to a new dict e.g. newD.

d =[{'a': 4}, {'b': 20}, {'c': 5}, {'d': 3}]

newD = {}
for entry in d:
    newD.update(entry)

>>> newD
{'c': 5, 'b': 20, 'a': 4, 'd': 3}

Note: If there are duplicate values in d the last one will be appear in newD.

Upvotes: 5

Related Questions