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

3
例如,我有一个包含四个字典的列表,如下所示:
[{'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个回答

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

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接