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': }, {'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.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值