Py学习  »  Python

csv到python字典

Zarmey • 5 年前 • 605 次点击  

对于家庭作业,我们被要求从csv构建一个字典(不导入csv或任何其他lib,只使用内置的python函数)。

csv看起来像这样:

Class mate, distance1, distance2, distance3, distance4
Bob, 102.5, 0.5587, 45.77, 49.225
Sally, 785.115, 32145.01, 4578.25, 0.5587
Anne, 4521.87, 12.5, 0.2547, 1545.554
...
...
...

我不断地出现价值错误,而且不会再进一步。

race_read = open('student_guess.csv', 'r')
race_open = race_read.readlines()

race_dict = {}

for line in race_open:
    key, val = line.strip().split('\n')
    race_dict[int(key)] = val

    print(race_dict)

下面是我得到的最后两行回溯:

key, val = line.strip().split('\n')
ValueError: not enough values to unpack (expected 2, got 1)

我希望字典看起来像这样:

{'Bob': [102.5, 0.5587, 45.77, 49.225], 'Sally': [785.115, .... etc], etc}
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/33241
 
605 次点击  
文章 [ 4 ]  |  最新文章 5 年前
Ruslan S.
Reply   •   1 楼
Ruslan S.    5 年前

Zarmey

更正后的代码可能如下所示:

for line in race_open[1:]: # 1
    splitline = line.split(',') # 2
    splitline = [s.strip() for s in splitline] # 3
    key, val = splitline[0], splitline[1:] # 4
    val = [float(v) for v in val] # 5
    race_dict[key] = val
print(race_dict)
  1. 如果不需要标题,请从2d行迭代race-open。

  2. 您应该拆分行,而不是在换行符\n'处,而是在逗号处。使用分割(′,))。

  3. 分裂后剥离。

  4. 在构建dict时,首先提供除 项目作为值[1:]。

  5. 从名称中拆分数值后,将其转换为浮点值

输出:

{'Bob': [102.5, 0.5587, 45.77, 49.225], 'Sally': [785.115, 32145.01, 4578.25, 0.5587], 'Anne': [4521.87, 12.5, 0.2547, 1545.554]}
MONTYHS
Reply   •   2 楼
MONTYHS    5 年前
race_read = open('student_guess.csv', 'r')
race_open = race_read.readlines()

race_dict = {}
count = 0
for line in race_open:
    if count==0:
        count = 1
        continue
    line = line.strip().split(',')
    race_dict[line[0]] = line[1:]
print(race_dict)

产量

{'Anne': [' 4521.87', ' 12.5', ' 0.2547', ' 1545.554'],
'Bob': [' 102.5', ' 0.5587', ' 45.77', ' 49.225'],
'Sally': [' 785.115', ' 32145.01', ' 4578.25', ' 0.5587']}
Tom Ron
Reply   •   3 楼
Tom Ron    5 年前

文件中的分隔符是逗号,因此-首先需要用逗号分隔-

res = line.strip().split(',')

这将给你一个由5个字符串组成的元组-

'Bob', '102.5', '0.5587', '45.77', '49.225'

如果你想像你描述的那样把它们添加到字典中,你必须做以下的事情-

race_dic[res[0]] = [float(res[1]), float(res[2]), float(res[3]), float(res[4])]
Devesh Kumar Singh
Reply   •   4 楼
Devesh Kumar Singh    5 年前

代码中的一些问题和建议:

  • 你在新线分裂 \n ,位于行的末尾,因此列表中只能有一个项目。您不能从中提取两个项目,因此您可以 ValueError: not enough values to unpack (expected 2, got 1) 错误
  • 你需要分开 , 而不是 \n ,因为值由 ,
  • 你可以使用 with 打开文件的上下文管理器
  • 您需要跳过文件的第一行,使用 next()
  • 你可以使用 extended iterable unpacking 输出名称和值,然后创建字典

将所有这些放在一起,重构的代码可能看起来像

race_dict = {}

#Use with to open the file
with open('file.txt', 'r') as race_read:

    #Skip the first line
    next(race_read)

    #Read all lines in a list
    race_open = race_read.readlines()

    #Iterate through the list
    for line in race_open:
        #Extract names and float values by splitting on ,
        key, *val = line.strip().split(',')

        #Convert all strings in val to float
        race_dict[key] = list(map(float, val))

print(race_dict)

所以如果输入文件是

Class mate, distance1, distance2, distance3, distance4
Bob, 102.5, 0.5587, 45.77, 49.225
Sally, 785.115, 32145.01, 4578.25, 0.5587
Anne, 4521.87, 12.5, 0.2547, 1545.554

输出将是

{'Bob': [102.5, 0.5587, 45.77, 49.225], 
'Sally': [785.115, 32145.01, 4578.25, 0.5587], 
'Anne': [4521.87, 12.5, 0.2547, 1545.554]}