1

嘿,我有像下面这样的字典

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]']
}

任何帮助!谢谢

4

1 回答 1

4

您可以使用set和 dict 理解:

>>> 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']}
于 2013-06-28T15:21:17.313 回答