Raj Rajeshwari Prasad
Raj Rajeshwari Prasad

Reputation: 334

Converting a Dataframe to Dictionary

I have a Dataframe in CSV format as shown in the picture.

enter image description here

I want to convert it into a dictionary such that rows are key and values are also corresponding row.

for this, I used the code:-

import pandas as pd
from ast import literal_eval

match_pairs = pd.read_csv('data_d.csv',usecols=['Object','Pairs'])
match_pairs['Pairs'] = match_pairs['Pairs'].apply(literal_eval)
dict = match_pairs.transpose()
dict.to_dict()
print(dict['a'])

When I imported the dataframe in match_pairs, the Pairs column got imported as a string rather than a list. therefore I used literal_eval() to get the structure of data.

Further, .to_dict() func converts column as a key. Therefore I transposed the data and then used the .to_dict() func.

but unfortunately, I am not able to get the key-value pairs as I require.
I wanted that for print(dict['a']), i get the value as ['d','e','f'].

Kindly, help me with this issue.

Upvotes: 1

Views: 51

Answers (1)

jezrael
jezrael

Reputation: 862471

First dont use dict for variable name, because builten, python code word.

Create Series and then use Series.to_dict:

match_pairs = pd.read_csv('data_d.csv',usecols=['Object','Pairs'])
match_pairs['Pairs'] = match_pairs['Pairs'].apply(literal_eval)

d = match_pairs.set_index('Object')['Pairs'].to_dict()

Or use zip with dict:

#reset builtin if used like variable
#import builtins
#dict = builtins.dict
d = dict(zip(match_pairs['Object'], match_pairs['Pairs']))

Upvotes: 2

Related Questions