Python 使用特定键从字典列表中删除重复项
因此,我有一个字典列表如下:Python 使用特定键从字典列表中删除重复项,python,list,dictionary,Python,List,Dictionary,因此,我有一个字典列表如下: a = [{'author':'John','country':'us','gender':'male'}, {'author':'Sean','country':'uk','gender':'male'}, {'author':'Sean','country':'russia','gender':'male'}, {'author':'Mike','country':'japan','gender':'male'}] 因此,现在,仅
a = [{'author':'John','country':'us','gender':'male'},
{'author':'Sean','country':'uk','gender':'male'},
{'author':'Sean','country':'russia','gender':'male'},
{'author':'Mike','country':'japan','gender':'male'}]
因此,现在,仅基于作者
我想从字典列表中删除重复项,而不考虑其他键值。输出应如下所示,删除条目3。(作者
重复)
请建议最短的路 我认为熊猫应该为我们做这件事:
将熊猫作为pd导入
df=pd.DataFrame(a,索引=None)
a=df.drop_duplicates(['author'])。到dict(orient='record'))
印刷品(a)
产出:
[{'author': 'John', 'country': 'us', 'gender': 'male'},
{'author': 'Sean', 'country': 'uk', 'gender': 'male'},
{'author': 'Mike', 'country': 'japan', 'gender': 'male'}]
或者,如果您关心内存,不想同时存储
a
和df
,请将数据帧创建到a
(a=pd.dataframe(a,index=None)
)。我想到的第一件事应该是:
list(dict([(elem['author'], elem) for elem in a]).values())
尽管可能存在一些更干净和/或更短的方法。使用一个集合来存储您已经看到的作者您搜索了什么,找到了什么?基于这一点,你们尝试了什么,是怎么失败的?请做一些研究,然后提问
list(dict([(elem['author'], elem) for elem in a]).values())