Mandroid
Mandroid

Reputation: 7524

panda: csv to dictionary

I have a csv file in following format:

id, category

1, apple

2, orange

3, banana

I need to read this file and populate a dictionary which has ids as key and categories as value.

I am trying to use panda, but its to_dict function us returning a dictionary with a a single key-value pair. Key is another dictionary containing 1,2,3 as entries and value too is a dictionary containing apple, orange, banana.

What I want is three key-value entriesm like 1 -> apple, 2 -> ornge, 3 -> banana.

Upvotes: 1

Views: 903

Answers (1)

jezrael
jezrael

Reputation: 863531

You can create index by first column and then convert Series df['category'] to dictionary:

df = pd.read_csv('file.csv', index_col=0)

d = df['category'].to_dict()

Or if only 2 columns csv is possible create Series by index_col=0 and squeeze=True parameters and convert to dicts:

d = pd.read_csv('file.csv', index_col=0, squeeze=True).to_dict()

Or if more columns and dont need index by first column use:

df = pd.read_csv('file.csv')

d = df.set_index('id')['category'].to_dict()

Upvotes: 2

Related Questions