2

I need a little help. I want to convert from dataframe into nested dictionaries.

    A   B    C
0   1   0    1.5
1   1   3,2  6.09
2   1   4    7.9
3   2   5    9.5
4   2   0    1.2
5   3   3    2.4

and i want to convert in this format:

dict={1:[{'0':1.5},{'3,2':6.09},{'4':7.9}],2:[{'5':9.5},{'0':1.2}],3:[{'3',2.4}]}

3 Answers 3

1

We can do groupby with agg dict items

d = df.set_index('B').groupby('A').agg(lambda x : [{k:v} for k, v in dict(x).items()])['C'].to_dict()
Out[574]: 
{1: [{'0': 1.5}, {'3,2': 6.09}, {'4': 7.9}],
 2: [{'5': 9.5}, {'0': 1.2}],
 3: [{'3': 2.4}]}
Sign up to request clarification or add additional context in comments.

Comments

0

This will give you a dictionary, remember dict is a key work in python so you have to use other variable name instead of dict. Here I used dict1.

dict1 = {1:[{'0':1.5, '3,2':6.09,'4':7.9}],2:[{'5':9.5,'0':1.2}],3:[{'3',2.4}]}

Comments

0

pretty similar to this solution:

df = df.set_index('B').groupby('A').apply(lambda x: [x['C'].to_dict()]).to_dict()

print(df)
'''
{1: [{'0': 1.5, '3,2': 6.09, '4': 7.9}],
 2: [{'5': 9.5, '0': 1.2}],
 3: [{'3': 2.4}]}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.