python从具有相同值的字典中删除那些键

时间:2013-06-28 15:17:28

标签: python python-2.7

嘿,我有词典,如下一个

dicts = {
'met_293':['81.0175','4','7','7','29.76','23','1','0','22','28.57','2','[KG]EHY' ],
'met_394':['79.9579','4','7','7','29.76','18','3','0','15','28.57','2','EHY[ILV]'],
'met_309':['81.0175','4','7','7','29.76','23','1','0','22','28.57','2','[KG]EHY' ],
'met_387':['79.9579','4','7','7','29.76','18','3','0','15','28.57','2','EHY[ILV]']
}

我想删除具有相同值的键,例如'met_293'和'met_309',这两个键在第12个位置具有相同的值,即'[KG] EHY'所以我希望我的字典像这样

{
'met_293':['81.0175','4','7','7','29.76','23','1','0','22','28.57','2','[KG]EHY'],
'met_394':['79.9579','4','7','7','29.76','18','3','0','15','28.57','2','EHY[ILV]']
}

任何帮助!!! 感谢

1 个答案:

答案 0 :(得分:4)

您可以使用set和词典理解:

>>> dicts = {'met_293': ['81.0175','4','7','7','29.76','23','1','0','22','28.57','2','[KG]EHY'],'met_394': ['79.9579','4','7','7','29.76','18','3','0','15','28.57','2','EHY[ILV]'],'met_309': ['81.0175','4','7','7','29.76','23','1','0','22','28.57','2','[KG]EHY'],'met_387': ['79.9579','4','7','7','29.76','18','3','0','15','28.57','2','EHY[ILV]']}
>>> seen = set()
>>> {k:v for k,v in dicts.iteritems() 
                                 if v[11] not in seen and not seen.add(v[11])}
{'met_394': ['79.9579', '4', '7', '7', '29.76', '18', '3', '0', '15', '28.57', '2', 'EHY[ILV]'],
 'met_293': ['81.0175', '4', '7', '7', '29.76', '23', '1', '0', '22', '28.57', '2', '[KG]EHY']}

以上代码相当于:

>>> dic = {}
>>> seen = set()
>>> for k,v in dicts.iteritems():
...     if v[11] not in seen:
...         dic[k] = v
...         seen.add(v[11])
...         
>>> dic
{'met_394': ['79.9579', '4', '7', '7', '29.76', '18', '3', '0', '15', '28.57', '2', 'EHY[ILV]'],
 'met_293': ['81.0175', '4', '7', '7', '29.76', '23', '1', '0', '22', '28.57', '2', '[KG]EHY']}