簡體   English   中英

Python - 從詞典列表中創建字典

[英]Python - create dictionary from list of dictionaries

我在Python中有一個字典列表

[
{'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 如果slug是重復的,如上例所示,它應該忽略它。 這可以通過復制其他條目或不同時重置它,我不打擾,因為它們應該是相同的。

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

實現這一目標的最佳方法是什么?

假設您的列表名為a ,則可以使用

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

在2.7以上的Python版本中,您可以使用

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

這將隱式刪除重復項(特別是通過使用給定鍵的最后一項)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM