简体   繁体   中英

Save CSV to dictionary with a list as the value using pandas

My CSV file looks something like this:

Version,1,2,3,4,5
Letter,A,B,C,D,E

Version and letter are both the keys I want in the dictionary which I read in using indexcol = 0. However, I want to save these values into a dictionary like this:

{Version: ["1,2,3,4,5"], Letter: ["A,B,C,D,E"]}

How would I do this using pandas? Thanks so much for your help.

Since you have the keys in rows, one simple way is to transpose the csv file and then converting columns to list followed by zip and to dictionary

df = pandas.read_csv("filename.csv").transpose()
dictionary = dict(zip(list(df.column_name1), list(df.column_name2)))

Other efficient way and if you have too many values in rows to enter each column name then you can try:

df = pandas.read_csv("filename.csv").transpose().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