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': }, {'max_score': u'110', 'total_mark': u'75', 'student': }],
[{'max_score': u'131', 'total_mark': u'99', 'student': }, {'max_score': u'131', 'total_mark': u'64', 'student': }],
[{'max_score': u'138', 'total_mark': u'110', 'student': }, {'max_score': u'138', 'total_mark': u'80', 'student': }]]
and i am trying to convert this record in their single individual records like:
['student': :[
{'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': :[
{'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': ''},
{'max_score': u'110', 'total_mark': u'75', 'student': ''}],
[{'max_score': u'131', 'total_mark': u'99', 'student': ''},
{'max_score': u'131', 'total_mark': u'64', 'student': ''}],
[{'max_score': u'138', 'total_mark': u'110', 'student': ''},
{'max_score': u'138', 'total_mark': u'80', 'student': ''}]]
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)
Output:
{('student', ''):
[{'max_score': '110', 'total_mark': '75'},
{'max_score': '131', 'total_mark': '99'},
{'max_score': '138', 'total_mark': '110'}],
('student', ''):
[{'max_score': '110', 'total_mark': '75'},
{'max_score': '131', 'total_mark': '64'},
{'max_score': '138', 'total_mark': '80'}]
}
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.