如果特定键的值为sam,则合并字典

2024-05-29 06:00:43 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,我有四本字典的列表,比如

[{'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}]

Tags: 数据列表字典usernamemathlabelabcchemistry
3条回答

下面是一个一次性解决方案,使用dict映射跟踪每个用户名的列表条目(假设dict列表存储在变量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}]

使用^{}

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

这有点冗长,但能把工作做完。你知道吗

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)。你知道吗

相关问题 更多 >

    热门问题