简体   繁体   中英

dictionary from csv file

So I have a csv file in the format:

  • a.year is all the years
  • a.category is all the categories
  • etc

There can be more or fewerthan four columns.

a.year,a.category,a.actor,a.title
2010,Actor-Leading Role,Colin Firth,The King's Speech
2010,Actor-Supporting Role,Christian Bale,The Fighter
2010,Actress-Leading Role,Natalie Portman,Black Swan
2010,Actress-Supporting Role,Melissa Leo,The Fighter
2009,Actor-Leading Role,Jeff Bridges,Crazy Heart

How would I make a dictionary that has keys as the headers and all the values below that key as aa list mapping to that key. Something like:

{a.year:['2010', '2010', '2010', '2010', '2009'], 
 ... and so on} 

for all the keys and values. Any ideas how to go about this?

So far I have tried to loop through the lines using a for loop but I don't know what to do next.

Try this--- Open the file, map the column as the value to the header:

f = open("data.csv","r")
lines = list(map(lambda x: x.split(","),f.readlines())
f.close()

dictionary = {}
for i in range(len(lines[0])): 
    dictionary[lines[0][i]] = list(map(lambda x:lines[x][i], range(1,len(lines))))

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