简体   繁体   English

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

[英]Python - create dictionary from list of dictionaries

I have a list of dictionaries in 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'}
]

I want to turn this list into a dictionary of dictionaries with the key being slug . 我想把这个列表变成一个词典字典,其中键是slug If the slug is duplicated as in the example above it should just ignore it. 如果slug是重复的,如上例所示,它应该忽略它。 This can either be by copying over the other entry or not bothing to reset it, I'm not bothered as they should be the same. 这可以通过复制其他条目或不同时重置它,我不打扰,因为它们应该是相同的。

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

What is the best way to achieve this? 实现这一目标的最佳方法是什么?

Assuming your list is called a , you can use 假设您的列表名为a ,则可以使用

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

In Python versions older than 2.7, you can use 在2.7以上的Python版本中,您可以使用

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

This will implicitly remove duplicates (specifically by using the last item with a given key). 这将隐式删除重复项(特别是通过使用给定键的最后一项)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM