从字典列表中删除具有重复值的字典 [英] Removing dicts with duplicate value from list of dicts

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

问题描述

我有一个字典列表,如下所示:

I have a list of dicts as follows:

[{'ppm_error': -5.441115144810845e-07, 'key': 'Y7', 'obs_ion': 1054.5045550349998},
{'ppm_error': 2.3119997582222951e-07, 'key': 'Y9', 'obs_ion': 1047.547178035},
{'ppm_error': 2.3119997582222951e-07, 'key': 'Y9', 'obs_ion': 1381.24928035},
{'ppm_error': -2.5532659838679713e-06, 'key': 'Y4', 'obs_ion': 741.339467035},
{'ppm_error': 1.3036219678359603e-05, 'key': 'Y10', 'obs_ion': 1349.712302035},
{'ppm_error': 3.4259216556970878e-06, 'key': 'Y6', 'obs_ion': 941.424286035},
{'ppm_error': 1.1292770047090912e-06, 'key': 'Y2', 'obs_ion': 261.156025035},
{'ppm_error': 1.1292770047090912e-06, 'key': 'Y2', 'obs_ion': 389.156424565},
{'ppm_error': 9.326980606898406e-06, 'key': 'Y5', 'obs_ion': 667.3107950350001}
]

我想删除具有重复键的字典,以便仅保留具有唯一键"的字典.哪个dict最终出现在最终列表中并不重要.因此,最终列表应如下所示:

I want to remove dicts with duplicate keys such that only dicts with unique 'key' remain. It doesn't matter which dict ends up in the final list. So the final list should look as follows:

[{'ppm_error': -5.441115144810845e-07, 'key': 'Y7', 'obs_ion': 1054.5045550349998},
{'ppm_error': 2.3119997582222951e-07, 'key': 'Y9', 'obs_ion': 1381.24928035},
{'ppm_error': -2.5532659838679713e-06, 'key': 'Y4', 'obs_ion': 741.339467035},
{'ppm_error': 1.3036219678359603e-05, 'key': 'Y10', 'obs_ion': 1349.712302035},
{'ppm_error': 3.4259216556970878e-06, 'key': 'Y6', 'obs_ion': 941.424286035},
{'ppm_error': 1.1292770047090912e-06, 'key': 'Y2', 'obs_ion': 261.156025035},
{'ppm_error': 9.326980606898406e-06, 'key': 'Y5', 'obs_ion': 667.3107950350001}
]

是否可以使用itertools.groupby函数来执行此操作,或者是否有另一种方法来解决此问题?有什么建议吗?

Is it possible to use itertools.groupby function for doing this or is there another way of approaching this problem? Any suggestions?

推荐答案

如果顺序很重要,则可以使用

If the order matters, then you can use collections.OrderedDict to collect all the items, like this

from collections import OrderedDict
print OrderedDict((d["key"], d) for d in my_list).values()

如果顺序无关紧要,您可以使用像这样的普通词典

And if the order doesn't matter, you can use a normal dictionary, like this

print {d["key"]:d for d in my_list}.values()

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

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