Python - create a dictionary from a list of dictionaries

I have a list of dictionaries in 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 slug key. If the pool is duplicated, as in the example above, it should just ignore it. It can be either by copying over another record, or without using reset, I'm not worried, 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?

+8
python
source share
1 answer

Assuming your list is called a , you can use

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

In versions of Python older than 2.7, you can use

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

This will implicitly remove duplicates (in particular, using the last item with the given key).

+21
source share

All Articles