Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - create dictionary from list of dictionaries

Tags:

python

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 key being slug. If the slug is duplicated as in the example above it should just ignore it. 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?

like image 810
John Avatar asked Feb 28 '12 12:02

John


People also ask

Can we convert list to dictionary in Python?

Since python dictionary is unordered, the output can be in any order. To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.

Can a dictionary contain a list Python?

Both can be nested. A list can contain another list. A dictionary can contain another dictionary. A dictionary can also contain a list, and vice versa.

How do I pass a list of dictionaries in Python?

We can also append a list of dictionaries with a new Python dictionary object as its element. We use the Python list append() method here. This is similar to appending a normal Python list. The only difference is that the argument which is passed to the append() method must be a Python dictionary.

How do you convert a list to a key value pair in Python?

By using enumerate() , we can convert a list into a dictionary with index as key and list item as the value. enumerate() will return an enumerate object. We can convert to dict using the dict() constructor.


1 Answers

Assuming your list is called a, you can use

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

In Python versions older than 2.7, you can use

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).

like image 124
Sven Marnach Avatar answered Oct 05 '22 22:10

Sven Marnach