How to normalize a dictionary of key and values pandas

My dictionary looks something like this: (has more data in the actual dictionary I’m working on)

dictionary = {'101020': {'name': 'HJ', 'grades': [90, 80, 70]}, '101520': {'name': ABC', 'grades': [100, 40, 70]}}

I want my dataframe to look like this:

code          name          grades
101020        HJ              90
101020        HJ              80
101020        HJ              70
101520        ABC             100
101520        ABC             40
101520        ABC             70

Currently I’m only able to get the name and data but not the code aka the key of the dictionary with this code:

vals = [val for val in dictionary.values())
df = pd.json_normalize(vals, 'grades', ['name']) I get the data without the key
print(df)

any help would be highly appreciated 🙂

>Solution :

Try explode after using pd.DataFrame.from_dict(),

df = pd.DataFrame.from_dict(dictionary, orient='index') \
   .explode('grades') \
   .rename_axis('code') \
   .reset_index()

df

Output:

output

Leave a Reply