合并python中字典列表中的重复项

时间:2018-02-10 10:39:03

标签: python list dictionary

我在python中有一个字典列表。现在我正在尝试根据python中的特定关键实体合并这些词典。字典列表的例子是:

[[{'max_score': u'110', 'total_mark': u'75', 'student': <student_details: Komal>}, {'max_score': u'110', 'total_mark': u'75', 'student': <student_details: Java>}],
 [{'max_score': u'131', 'total_mark': u'99', 'student': <student_details: Komal>}, {'max_score': u'131', 'total_mark': u'64', 'student': <student_details: Java>}],
 [{'max_score': u'138', 'total_mark': u'110', 'student': <student_details: Komal>}, {'max_score': u'138', 'total_mark': u'80', 'student': <student_details: Java>}]]

我试图将这条记录转换为单个记录,如:

    ['student': <student_details: Komal>:[
{'max_score': u'110', 'total_mark': u'75', }
{'max_score': u'131', 'total_mark': u'99'},
{'max_score': u'138', 'total_mark': u'110'}],
'student': <student_details: Java>:[
{'max_score': u'110', 'total_mark': u'75'}, 
{'max_score': u'131', 'total_mark': u'64'}, 
{'max_score': u'138', 'total_mark': u'80'}]]

请建议我如何实现这一目标。提前谢谢。

1 个答案:

答案 0 :(得分:3)

可能最接近您的预期输出的是:

studs = [
 [{'max_score': u'110', 'total_mark': u'75', 'student': '<student_details: Komal>'}, 
  {'max_score': u'110', 'total_mark': u'75', 'student': '<student_details: Java>'}], 
 [{'max_score': u'131', 'total_mark': u'99', 'student': '<student_details: Komal>'}, 
  {'max_score': u'131', 'total_mark': u'64', 'student': '<student_details: Java>'}], 
 [{'max_score': u'138', 'total_mark': u'110', 'student': '<student_details: Komal>'}, 
  {'max_score': u'138', 'total_mark': u'80', 'student': '<student_details: Java>'}]]


d={}
for studlist in studs:
    for stud in studlist:
        # use the 'student' - entry as tuple as key and append a set of each scores data
        d.setdefault( ('student',stud['student']) , []).append(
            { 'max_score' : stud['max_score'], 'total_mark': stud['total_mark'] })

print(d)

输出:

{('student', '<student_details: Komal>'): 
    [{'max_score': '110', 'total_mark': '75'}, 
     {'max_score': '131', 'total_mark': '99'}, 
     {'max_score': '138', 'total_mark': '110'}], 
('student', '<student_details: Java>'): 
    [{'max_score': '110', 'total_mark': '75'}, 
     {'max_score': '131', 'total_mark': '64'}, 
     {'max_score': '138', 'total_mark': '80'}]
} 

哪一组tupleskey,元组为('student', 'your details'),而list的值为dict。你需要一个hashable类型作为dict的键 - 元组是不可变的,因此可以作为密钥进行清理和有效。