Maximilian Kindshofer
Maximilian Kindshofer

Reputation: 2843

Combine Dictionarys in a list based on a value

I can't get my head around this problem:

I have a List:

[{'name' : 'Bob', 'Salary2014' : 2000}, {'name': 'Alice', 'Salary2014' : 1000}, {'name':'Bob', 'Salary2013' : 1500}]

I want to join the dictionarys on base of the Name (which is unique)

[{'name' : 'Bob', 'Salary2014' : 2000, 'Salary2013' : 1500}, {'name': 'Alice', 'Salary2014' : 1000}]

I know the solution has to be simple and may involve the .update method, but I just don't get it.

Upvotes: 0

Views: 36

Answers (2)

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29093

The other pretty similar way is to use defaultdict:

from collections import defaultdict

inp = [{'name': 'Bob', 'Salary2014': 2000},
       {'name': 'Alice', 'Salary2014': 1000},
       {'name': 'Bob', 'Salary2013': 1500}]

out = defaultdict(dict)

for rec in inp:
    out[rec['name']].update(rec)

print out.values()

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121494

Use a new dictionary to track your dictionaries based on name:

combined = {}
for d in yourlist:
    combined.setdefault(d['name'], {}).update(d)

output = combined.values()

The combined.setdefault() method here sets {} as a default value if d['name'] is not present, then updates the dictionary with the current iteration.

If you are using Python 3, use list(combined.values()).

Demo:

>>> yourlist = [{'name' : 'Bob', 'Salary2014' : 2000}, {'name': 'Alice', 'Salary2014' : 1000}, {'name':'Bob', 'Salary2013' : 1500}]
>>> combined = {}
>>> for d in yourlist:
...     combined.setdefault(d['name'], {}).update(d)
... 
>>> combined.values()
[{'Salary2013': 1500, 'name': 'Bob', 'Salary2014': 2000}, {'name': 'Alice', 'Salary2014': 1000}]

Upvotes: 1

Related Questions