Sometimes we have a list of dictionaries, and we need to lookup a dictionary by a particular key. This can be the case with database query results or data read from a csv.
Goal: Convert a list of dictionaries to a nested dictionary, so we can look up elements by their id.
The initial data is structured like this:
data_list = [
{'id': '1', 'name': ...},
{'id': '2', 'name': ...},
{'id': '3', 'name': ...},
...
]
If we need to lookup rows by id
, we could search the list, but that would be inefficient for multiple lookups. A better way is to convert the list of dictionaries to a dictionary, where the key is the id.
data_dict = {
'1': {'id': '1', 'name': ...},
'2': {'id': '2', 'name': ...},
'3': {'id': '3', 'name': ...},
}
Now we can easily and efficiently lookup dictionaries by their id.
some_dict = data_dict[id]
So how do we accomplish this?
Using a for
loop
data_dict = {}
for item in data_list:
data_dict[item['id']] = item
We iterate over the list, grabbing the id
from each item. Then we create a new dictionary key and value during each iteration.
This is not too bad, but we can simplify even more using dictionary comprehension.
Using dictionary comprehension
data_dict = {d['id']: d for d in data_list}
Hopefully you can see how both examples accomplish the same thing. They both include the same components, but the second example is cleaner.