Merge dictionaries if value of a particular key is same

Viewed 78

For example I have list of four dictionaries like

[{'username': 'xyz', 'label':'chemistry', 'marks': 56},
 {'username': 'abc', 'label':'chemistry', 'marks': 95},
 {'username': 'xyz', 'label':'math', 'marks': 43},
 {'username': 'abc', 'label':'math', 'marks': 87}]

I want transform the data so that I can get data as

[{'username': 'xyz', 'chemistry': 56, 'math': 43},
 {'username': 'abc', 'chemistry': 95, 'math': 87}]
3 Answers

Here is a one-pass solution, using a dict mapping to keep track of the list entry for each username when it is appended (assuming your list of dicts is stored in variable l):

m = []
d = {}
for i in l:
    u = i['username']
    if u not in d:
        m.append({'username': u})
        d[u] = m[-1]
    d[u][i['label']] = i['marks']

m will become:

[{'username': 'xyz', 'chemistry': 56, 'math': 43}, {'username': 'abc', 'chemistry': 95, 'math': 87}]

Using collections.defaultdict:

from collections import defaultdict

L = [{'username': 'xyz', 'label':'chemistry', 'marks': 56},
     {'username': 'abc', 'label':'chemistry', 'marks': 95},
     {'username': 'xyz', 'label':'math', 'marks': 43},
     {'username': 'abc', 'label':'math', 'marks': 87}]

dd = defaultdict(lambda: defaultdict(int))

for i in L:
    dd[i['username']][i['label']] = i['marks']

res = [{'username': k, **v} for k, v in dd.items()]

[{'username': 'xyz', 'chemistry': 56, 'math': 43},
 {'username': 'abc', 'chemistry': 95, 'math': 87}]

This is a little verbose but it'll get the job done.

usersDict = {}
for item in listOfDicts:
    if (item['username'] in dict):
        usersDict[item['username']][item['label']] = item['marks']
    else:
        usersDict[item['username']] = { 
            'username': item['username']
            item['label']: item['marks'] 
        }
result = list(userDict.values())

Note that I'm using a dictionary here because lookup on a dictionary is O(1) instead of O(n) on a list.

Related