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?
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.
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With