在Python中合并字典列表中的重复项
我有一个python词典列表.现在,我正在尝试基于python中的特定键实体合并这些字典.字典列表的示例是:
I have a list of dictionaries in python. And now i am trying to merge these dictionaries based on a specific key entity in python. Example the list of dictionary is:
[[{'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>}]]
我正在尝试将此记录转换为单个记录,例如:
and i am trying to convert this record in their single individual records like:
['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'}]]
请给我建议我该如何实现.预先感谢.
please suggest me how can i achieve that. Thanks in advance.
可能最接近预期输出的是:
Probably the closest you could come to your expected output is:
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'}]
}
这是一个以tuples
作为key
的集合,元组是('student', 'your details')
,而您的得分中dict
的list
值.您需要一个可哈希的类型作为dict的键-元组是不可变的,因此可哈希且可作为键有效.
Which is a set with tuples
as key
, the tuples are ('student', 'your details')
and values of list
of dict
of your scores. You need a hashable type as key into a dict - tuples are immutable and thus hashable and valid as key.