如果特定键的值相同,则合并字典

时间:2018-10-30 20:29:58

标签: python python-3.x list dictionary

例如,我有四个字典的列表,例如

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

我想转换数据,以便可以像

那样获取数据
[{'username': 'xyz', 'chemistry': 56, 'math': 43},
 {'username': 'abc', 'chemistry': 95, 'math': 87}]

3 个答案:

答案 0 :(得分:2)

这是一个一站式解决方案,使用字典映射来跟踪每个用户名附加后的列表条目(假设您的字典列表存储在变量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将变为:

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

答案 1 :(得分:2)

使用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}]

答案 2 :(得分:0)

这有点冗长,但是可以完成工作。

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())

请注意,我在这里使用字典是因为字典上的查找是O(1)而不是列表上的O(n)。

相关问题