2012-02-28 90 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) 

這將隱含刪除重複(特別是通過使用最後具有給定鍵的項目)。