Brightscales
Brightscales

Reputation: 43

Pandas dataframe to dict, while keeping duplicate rows

I have a dataframe that looks like this:

kenteken status code
0      XYZ      A  123
1      XYZ      B  456
2      ABC      C  789

And I want to convert it to a dictionary in a dictionary like this:

{'XYZ':{'code':'123', 'status':'A'}, {'code':'456', 'status':'B'}, 'ABC' : {'code':'789', 'status:'C'}}

The closest I've been able to come was the folling:

df.groupby('kenteken')['status', 'code'].apply(lambda x: x.to_dict()).to_dict()

Which yields:

{'ABC': {'status': {2: 'C'}, 'code': {2: '789'}},'XYZ': {'status': {0: 'A', 1: 'B'}, 'code': {0: '123', 1: '456'}}}

Which is close but not quite. I really don't know what to do anymore, so appreciate any help!

Upvotes: 3

Views: 2759

Answers (1)

user96564
user96564

Reputation: 1607

Does this work for you?

a = dict(df.set_index('kenteken').groupby(level = 0).\
    apply(lambda x : x.to_dict(orient= 'records')))

print(a)

{'ABC': [{'status': 'C', 'code': 789}], 'XYZ': [{'status': 'A', 'code': 123}, {'status': 'B', 'code': 456}]}

Upvotes: 6

Related Questions