Reputation: 11
id GIVEN_NAMES FAMILY_NAME DATE_OF_BIRTH
0 tttyy12 8000004199 8000004199 19660410
1 tttyy13 8000004274 8000004274 19980209
This is a dataframe output
I need to convert this into dict
{'tttyy12': ['8000004199','8000004199','19660410'], 'tttyy13' : ['8000004274' ,'8000004274' , '19980209']}
Upvotes: 1
Views: 3770
Reputation: 4863
I know it's an old question, however, another option is to use the pd.DataFrame.groupby()
.
dict([(key, value) for (key, value) in dt.groupby("id")])
Upvotes: 0
Reputation: 30002
Use apply()
on rows and convert row value to list with Series.values.tolist()
.
l = df.set_index('id').apply(lambda row: {row.name: row.values.tolist()}, axis=1).tolist()
print(l)
[{'tttyy12': [8000004199, 8000004199, 19660410]}, {'tttyy13': [8000004274, 8000004274, 19980209]}]
Upvotes: 2
Reputation: 36598
You can set the index to the id
column, then convert to an index-based dictionary. From there you can use a comprehension to turn the value dictionaries to lists.
{
k: list(v.values())
for k, v
in df.set_index('id').to_dict('index').items()
}
# returns:
{'tttyy12': [8000004199, 8000004199, 19660410],
'tttyy13': [8000004274, 8000004274, 19980209]}
Upvotes: 0