
Dictionary to DataFrame and back to Dictionary
This sample code shows how to create a DataFrame dataset from a Dictionary, convert it to a Dictionary in order to perform some operations and then convert it back to a DataFrame.
# library
import pandas as pd
# create sample dataset from dictionary
data = pd.DataFrame({'name': ['Tom', 'Ali', 'Dammy', 'Dave', 'Ayo', 'Kenny', 'Jamil', 'Eri', 'Navee', 'Dan'],
'grade': [1, 2, 3, 1, 2, 3, 1, 2, 3, 1]})
print(data) # print dataset
print(" ")
# convert dataframe to dictionary which gives a common key to keys with same value
df_to_dict = data.to_dict(orient='records')
print(df_to_dict) # print output
dict_data = {} # initiate an empty dictionary
for row in df_to_dict:
if row['grade'] in dict_data.keys():
dict_data[row['grade']].append(row['name'])
else:
dict_data[row['grade']] = []
dict_data[row['grade']].append(row['name'])
print(" ")
print(dict_data)
# convert dictionary to dataframe
df = pd.DataFrame([(k, v) for k, v in dict_data.items()], columns=['grade', 'name'])
df['population'] = df['name'].str.len() # get count of names in each grade
df