根据类似的特定值合并字典

时间:2018-02-12 07:26:12

标签: python list dictionary merge

我正在尝试根据类似的特定值合并字典。目前我有这本词典:

    [{'max_score': '110', 'total_mark': '75', 'id': 1},
     {'max_score': '110', 'total_mark': '75', 'id': 2},
     {'max_score': '131', 'total_mark': '99', 'id': 1}, 
     {'max_score': '131', 'total_mark': '64', 'id': 2}]

我试图将它们合并为:

    ['id': '1',
     'rec':[
             {'max_score': '110', 'total_mark': '75'},
             {'max_score': '131', 'total_mark': '99'}
           ],

     'id': '2',
     'rec':[
            {'max_score': '110', 'total_mark': '75'}, 
            {'max_score': '131', 'total_mark': '64'}
           ]
    ]

请帮助。提前谢谢。

2 个答案:

答案 0 :(得分:1)

您可以使用简单的forloop

来完成
x = [{'max_score': '110', 'total_mark': '75', 'id': 1},
     {'max_score': '110', 'total_mark': '75', 'id': 2},
     {'max_score': '131', 'total_mark': '99', 'id': 1}, 
     {'max_score': '131', 'total_mark': '64', 'id': 2}]

d = {}
for i in x:
    if i["id"] not in d:
        d[i["id"]] = {'rec': [{'max_score': i['max_score'], 'total_mark': i['total_mark']}]}
    else:
        d[i["id"]]['rec'].append({'max_score': i['max_score'], 'total_mark': i['total_mark']})

print d

<强>输出

{1: {'rec': [{'total_mark': '75', 'max_score': '110'}, {'total_mark': '99', 'max_score': '131'}]}, 2: {'rec': [{'total_mark': '75', 'max_score': '110'}, {'total_mark': '64', 'max_score': '131'}]}}

答案 1 :(得分:1)

    dict_data = {}
    for  val in data:
        score, mark, id_ = val
        if val[id_] in dict_data:
            dict_data[val[id_]]['rec'].append({"max_score":val[score],"total_mark":val[mark]})
        else:
            dict_data.setdefault(val[id_],{'rec':[{"max_score":val[score],"total_mark":val[mark]}]})
>>>{1: {'rec': [{'max_score': '75', 'total_mark': '110'},
                {'max_score': '99', 'total_mark': '131'}]},
   2: {'rec': [{'max_score': '75', 'total_mark': '110'},
               {'max_score': '64', 'total_mark': '131'}]}}