Daniel
Daniel

Reputation: 395

Dataframe to dictionary Python

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

Upvotes: 0

Views: 37

Answers (2)

Audrey
Audrey

Reputation: 71

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 :)

Upvotes: 1

oskros
oskros

Reputation: 3285

Group into a list and then convert to dict:

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

Upvotes: 1

Related Questions