Skip to content Skip to sidebar Skip to footer

Dataframe To Dict With One Column As The Key And Multiple Columns As A Value

id GIVEN_NAMES FAMILY_NAME DATE_OF_BIRTH 0 tttyy12 8000004199 8000004199 19660410 1 tttyy13 8000004274 8000004274 19980209 This is a datafram

Solution 1:

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]}

Solution 2:

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]}]

Post a Comment for "Dataframe To Dict With One Column As The Key And Multiple Columns As A Value"