Flatten list of dictionaries with multiple key, value pairs

Viewed 365

I have a list of dictionaries with multiple KVP each

list_dict = [{'id': 1, 'name': 'sana'}, {'id': 2, 'name': 'art'}, {'id': 3, 'name': 'tiara'}]

I want to transform this into this format:

final_dict = {1: 'sana', 2: 'art', 3: 'tiara'}

I've been trying dict comprehensions but it does not work. Here's the best that I could do:

{k:v for d in list_dict for k, v in d.items()}
4 Answers

You don't need d.items(), you can just access the id and name properties of each dict.

{d['id']: d['name'] for d in list_dict}

for each element of the list you want the d["id"] to be the key and d["name"] to be the value, so the dictionary comprehension would look like this:

{d["id"]: d["name"] for d in list_dict}

You can try

final_dict={} 
for dico in list_dict:
    final_dict[dico['id']] = dico['name'] 

There's probably a few different ways you can do this. Here's a nice simple way of doing it using a pandas dataframe:

import pandas as pd
df = pd.DataFrame(list_dict) # <- convert to dataframe
df = df.set_index('id') # <- set the index to the field you want as the key
final_dict = df['name'].to_dict() # <- convert the series 'name' to a dict
print(final_dict)

{1: 'sana', 2: 'art', 3: 'tiara'}
Related