Python - 从词典列表中创建字典

时间:2012-02-28 12:26:31

标签: python

我在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'}
}

实现这一目标的最佳方法是什么?

1 个答案:

答案 0 :(得分:22)

假设您的列表名为a,您可以使用

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

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

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

这将隐式删除重复项(特别是使用带有给定键的 last 项)。