2012-02-28 89 views
8

的列表字典我有在PythonPython的 - 创建词典

[ 
{'id':'1', 'name': 'test 1', 'slug': 'test1'}, 
{'id':'2', 'name': 'test 2', 'slug': 'test2'}, 
{'id':'3', 'name': 'test 3', 'slug': 'test3'}, 
{'id':'4', 'name': 'test 4', 'slug': 'test4'}, 
{'id':'5', 'name': 'test 5', 'slug': 'test4'} 
] 

词典列表我想打开这个名单变成字典键为slug的字典。如果slu is如上面的例子那样重复,它应该忽略它。这可以通过复制其他条目或不重复它,我不打扰,因为它们应该是相同的。

{ 
'test1': {'id':'1', 'name': 'test 1', 'slug': 'test1'}, 
'test2': {'id':'2', 'name': 'test 2', 'slug': 'test2'}, 
'test3': {'id':'3', 'name': 'test 3', 'slug': 'test3'}, 
'test4': {'id':'4', 'name': 'test 4', 'slug': 'test4'} 
} 

达到此目的的最佳方法是什么?

回答

20

假设你的列表被称为a,您可以使用

my_dict = {d["slug"]: d for d in a} 

在比2.7老的Python版本中,你可以使用

my_dict = dict((d["slug"], d) for d in a) 

这将隐含删除重复(特别是通过使用最后具有给定键的项目)。