Reputation: 97
I am working on a problem where list of dictionaries have same keys and I want to aggregate all the values into a list for every key.
x = [
{'firstName': 'Tom', 'lastName': 'Fyre', 'email': 'tom_f@gmail'},
{'firstName': 'Jerry', 'lastName': 'Brat', 'email': 'jerry_b@gmail'},
{'firstName': 'Phil', 'lastName': 'Hughes', 'email': 'phil_h@gmail'}
]
I want to convert above list of dictionaries to one dictionary which looks like:
results = {
'firstName': ['Tom', 'Jerry', 'Phil'],
'lastName': ['Fyre', 'Brat', 'Hughes'],
'email': ['tom_f@gmail', 'jerry_b@gmail', 'phil_h@gmail']
}
Upvotes: 1
Views: 222
Reputation: 862481
I think you need to_dict
with parameter orient='list'
:
df1 = pd.DataFrame(x)
print (df1)
email firstName lastName
0 tom_f@gmail Tom Fyre
1 jerry_b@gmail Jerry Brat
2 phil_h@gmail Phil Hughes
results = df1.to_dict(orient='list')
print (results)
{'firstName': ['Tom', 'Jerry', 'Phil'],
'email': ['tom_f@gmail', 'jerry_b@gmail', 'phil_h@gmail'],
'lastName': ['Fyre', 'Brat', 'Hughes']}
Upvotes: 4