简体   繁体   English

将csv文件读入嵌套列表的字典中

[英]reading a csv file into a dictionary of nested lists

I have a CSV file of sat scores in the format: 我有一个SAT成绩的CSV文件,格式为:

State Rate Verbal Math 州利率语言数学

and the corresponding values for all fifty states. 以及所有五十个州的对应值。 I need a dictionary. 我需要字典。 The dictionary format for data is the column names as the key and then data under each as lists of the values for that key.I am able to print the list out in the proper format but the lists are not linked to the keys in the dictionary and the dictionary is there, but empty. 数据的字典格式是将列名作为键,然后将每个数据下的数据作为该键的值列表。我能够以正确的格式打印列表,但列表未链接到字典中的键字典在那里,但是空的。 After many attempts at different methods, this is the best I've come up with: 在尝试了不同的方法之后,这是我所能想到的最好的方法:

with open('../sat_scores.csv', mode='r') as f:
    sat= {}                                          
    label_line =[]                                  
    reader = csv.reader(f)                           
    count = 0                                        
    for row in reader:                 
        print(row)
        if count == 0:                                
           for item in row:                           
               item = sat.keys                       
        count +=1                                  
    for row in reader:
        for key in sat.keys:                      
            for score in row:                     
                sat[key].append(score)
    print(sat)                            

Any suggestions? 有什么建议么?

Assuming your rows are unique, this should do it: 假设您的行是唯一的,则应该这样做:

with open('../sat_scores.csv', mode='r') as f:
    sat = {}                                                                                        
    for row in csv.reader(f):                 
        sat[row[0]] = row[1:]

row is a list. row是一个列表。 row[0] has the name of your state. row[0]具有您所在州的名称。 row[1] , row[2] and row[3] have everything else. row[1]row[2]row[3]还有其他所有内容。 You can use list slicing and make an entry of State : <List of data> . 您可以使用列表切片并输入State : <List of data>

And you're done. 这样就完成了。 It would be good to know that item = sat.keys does not do what you expect. 最好知道item = sat.keys不能达到您的期望。 keys is a function of the dict, and you are assigning the function to a variable. keys是dict的函数,您正在将该函数分配给变量。 Look at this: 看这个:

>>> sat = {}
>>> sat.keys
<built-in method keys of dict object at 0x101b81c08>

What you should be doing is something along these lines: 您应该做的是遵循这些方针:

>>> row = ['OH', '88%', 200, 180]
>>> sat[row[0]] = row[1:]
>>> sat
{'OH': ['88%', 200, 180]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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