例如,我有四个字典的列表,例如
[{'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}]
解决方法:
这是一个一站式解决方案,使用字典映射来跟踪每个用户名添加后的列表条目(假设您的字典列表存储在变量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}]
标签:python-3-x,list,dictionary,python
来源: https://codeday.me/bug/20191024/1924404.html