0

I'm looking to turn two columns in a dataframe into a dictionary, column_a holds the item, and column_b has the description:

column_a     column_b
---------------------
Furniture    Table
Furniture    Chair
Tech         Laptop
Tech         Screen

And the result should be:

{'Furniture':['Table','Chair'], 'Tech' : ['Laptop', 'Screen']}

2 Answers 2

1

You'll want to use a groupby statement, like this:

def turn_df_into_dict(df):
    
    output_dict = {}
    
    for name, group in df.groupby('column_a'):
        output_dict[name] = group['column_b']
        
    return output_dict

This should give you the intended output :)

Sign up to request clarification or add additional context in comments.

1 Comment

Yep, that's good, however, it does not deal with repeated values in 'column_b' so I added a .unique() :) thanks
1

Group into a list and then convert to dict:

dct = df.groupby('column_a')['column_b'].apply(list).to_dict()

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.