1

first post!

I am trying to create a function that create dictionary in loop from a dataframe. Assume those 2 simplistic dataframes already exist:

data1 = {'A':[1, 2, 3, 4], 'B':[5, 6, 7, 8]}
df1 = pd.DataFrame(data) 

dataframe1

1

and

data2 = {'C':[9, 10], 'D':[11, 12], 'E':[13, 14] }
df2 = pd.DataFrame(data2)

dataframe2

2

I want to be able to create a function like this:

def create_dict(df):

where the end results of df1 is:

dict1 = { 'A' : 1, 'B' : 5}
dict2 = { 'A' : 2, 'B' : 6}
dict3 = { 'A' : 3, 'B' : 7}
dict4 = { 'A' : 4, 'B' : 8}

and the end results of df2 is:

dict1 = { 'C' : 9, 'D' : 11, 'E' : 13}
dict2 = { 'C' : 10, 'D' : 12, 'E' : 14}

I was looking at dictionary comprehension to handle this, but I'm obviously not sure how to handle that problem. Thanks!

1 Answer 1

1

Use pandas.DataFrame.to_dict with records:

df1.to_dict(orient="records")

Output:

[{'A': 1, 'B': 5}, {'A': 2, 'B': 6}, {'A': 3, 'B': 7}, {'A': 4, 'B': 8}]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Chris, beautiful and simple!

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.