猿问

根据值组合字典

我有一个看起来像这样的字典列表

[{"Name": John, "Score": 1}, {"Name": John, "Score": 2}, {"Name": Steve, "Score": 3}, {"Name": Steve, "Score": 4}]

我怎样才能像这样组合这些字典呢?

[{"Name": John, "Score": [1,2]},{"Name": Steve, "Score": [3,4]}]



交互式爱情
浏览 109回答 2
2回答

人到中年有点甜

lst = [{"Name": "John", "Score": 1}, {"Name": "John", "Score": 2}, {"Name": "Steve", "Score": 3}, {"Name": "Steve", "Score": 4}]out = {}for d in lst:    out.setdefault(d['Name'], []).append(d['Score'])out = [{'Name': k, 'Score': v} for k, v in out.items()]print(out)印刷:[{'Name': 'John', 'Score': [1, 2]}, {'Name': 'Steve', 'Score': [3, 4]}]

largeQ

使用itertoolsdef combine(group):    out = {}    out['Name'] = group[0]['Name']    score = []    for sub in group:        score.append(sub['Score'])    out['Score'] = score    return outgrouped = map(combine,[list(v) for k,v in groupby(x, lambda x: x['Name'])])print(list(grouped))[{'Name': 'John', 'Score': [1, 2]}, {'Name': 'Steve', 'Score': [3, 4]}]
随时随地看视频慕课网APP

相关分类

Python
我要回答