14

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?

John
  • 21,047
  • 43
  • 114
  • 155

2 Answers2

28

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

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
1
In [1]: import collections
   ...:
   ...: l = [{'a':1},{'b':2}]
   ...: d = dict(collections.ChainMap(*l))

In [2]: d
Out[2]: {'b': 2, 'a': 1}
8c6b5df0d16ade6c
  • 1,910
  • 15
  • 15