简体   繁体   中英

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 aa 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM