python列表的字典根据价值找到重复的 [英] python list of dictionaries find duplicates based on value

查看:97
本文介绍了python列表的字典根据价值找到重复的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python 2.7中有一个列表。

  a = [{'id':1,'desc':'smth'},
{'id ':2,'desc':'smthelse'},
{'id':1,'desc':'smthelse2'},
{'id':1,'desc':'smthelse3 '},....]

我想通过列表,找到那些具有相同的值 - id(例如id = 1)并创建一个新的dict

  b = [{'id':1 ,'desc':[smth,smthelse2,smthelse3]},
{'id':2,'desc':'smthelse'}]

我希望我很清楚



非常感谢你的建议

解决方案

即使它们只包含一个元素,最好将desc值保持为列表。这样你可以在b中为d中的


  
print d ['id']
在d ['desc']中描述:
print desc

这也适用于字符串只需返回个人字符,这不是你想要的。



现在,该解决方案为您提供列表列表列表:

  a = [{'id':1,'desc':'smth'},{'id':2,'desc':'smthelse'}, {'id':1,'desc':'smthelse2'},{'id':1,'desc':'smthelse3'}] 

c = {}
for d a:
c.setdefault(d ['id'],[])。append(d ['desc'])
b = [{'id':k,'desc':v} k,v in c.iteritems()]

b 现在:

  [{'desc':['smth','smthelse2','smthelse3'], 'id':1},
{'desc':['smthelse'],'id':2}]


I have a list of dicts in python 2.7.

a =[{'id': 1,'desc': 'smth'},
    {'id': 2,'desc': 'smthelse'},
    {'id': 1,'desc': 'smthelse2'},
    {'id': 1,'desc': 'smthelse3'},....]

I would like to go trough the list and find those dicts that have the same value - id (e.g. id = 1) and create a new dict

b = [{'id':1, 'desc' : [smth, smthelse2,smthelse3]}, 
     {'id': 2, 'desc': 'smthelse'}]

I hope I was clear enough

thank you very much for your suggestions

解决方案

It is better to keep the "desc" values as lists everywhere even if they contain a single element only. This way you can do

for d in b:
    print d['id']
    for desc in d['desc']:
        print desc

This would work for strings too, just returning individual characters, which is not what you want.

And now the solution giving you a list of dicts of lists:

a =[{'id': 1,'desc': 'smth'},{'id': 2,'desc': 'smthelse'},{'id': 1,'desc': 'smthelse2'},{'id': 1,'desc': 'smthelse3'}]

c = {}
for d in a:
    c.setdefault(d['id'], []).append(d['desc'])
b = [{'id': k, 'desc': v} for k,v in c.iteritems()]

b is now:

[{'desc': ['smth', 'smthelse2', 'smthelse3'], 'id': 1},
 {'desc': ['smthelse'], 'id': 2}]

这篇关于python列表的字典根据价值找到重复的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆