简体   繁体   English

Python:文件内容到字典

[英]Python: file contents to dictionary

Write a function that accepts a filename(string) of a CSV file which contains the information about student's names and their grades for four courses and returns a dictionary of the information. 编写一个函数,接受CSV文件的文件名(字符串),其中包含有关学生姓名及其四门课程成绩的信息,并返回信息字典。 The keys of the dictionary should be the name of the students and the values should be a list of floating point numbers of their grades. 字典的键应该是学生的名字,值应该是他们成绩的浮点数列表。 For example, if the content of the file looks like this: 例如,如果文件的内容如下所示:

Mark,90,93,60,90
Abigail,84,50,72,75
Frank,46,83,53,79
Yohaan,47,77,74,96

then your function should return a dictionary such as: 那么你的函数应该返回一个字典,如:

out_dict = {'Frank': [46.0, 83.0, 53.0, 79.0],
            'Mark': [90.0, 93.0, 60.0, 90.0],
            'Yohaan': [47.0, 77.0, 74.0, 96.0],
            'Abigail': [84.0, 50.0, 72.0, 75.0]}

This is my code: 这是我的代码:

def dict_from_file (file_name):
    file_pointer = open(file_name, 'r')
    data = file_pointer.readlines()
    print (data)
    output_dict = {}
    for line in data:

    file_pointer.close()
    return (output_dict)

#Main Program
file_name = input("Enter the exact file name with its extension (.i.e., .txt): ")
result = dict_from_file (file_name)
print (result)

As you can see the statements are missing inside the for loop. 如您所见,for循环中缺少语句。 The problem is I cannot find any logic to first take the input from the file and paste it in a dictionary. 问题是我找不到任何逻辑来首先从文件中获取输入并将其粘贴到字典中。 And if I plan to extract each line once how will I add it to the dictionary with name as the key and the four numbers as the values? 如果我计划提取每一行,我将如何将其添加到字典中,其中名称为键,四个数字为值?

To strictly focus on your code: 要严格关注您的代码:

If you print out what you've read, you will notice you have this: 如果你打印出你读过的内容,你会发现你有这个:

['Mark,90,93,60,90\n', 'Abigail,84,50,72,75\n', 'Frank,46,83,53,79\n', 'Yohaan,47,77,74,96']

So, when you are iterating through each item in your list, to keep this example simple, you can pretty much extract the first item, which will now be your key, and then take the part of the list that excludes the name and cast each item to a float. 因此,当您遍历列表中的每个项目时,为了简化此示例,您几乎可以提取第一个项目,现在将是您的密钥,然后将列表中的一部分排除在名称之外项目到浮动。

So, you pretty much are looking for: 所以,你几乎都在寻找:

l = line.split(',')
output_dict[l[0]] = map(float, l[1:])

What is happening up there is that you are taking each item you are iterating over, making it a list, by splitting on ','. 正在发生的事情是,你正在把你正在迭代的每个项目,通过拆分','成为一个列表。 Then you are going to take the first item in the list and make that your key. 然后,您将获取列表中的第一项,并将其作为您的密钥。 Then to assign your value, you have to make use of the map method, which will map out each item in your list to a float. 然后要分配您的值,您必须使用map方法,该方法会将list中的每个项目映射到浮点数。

You are going to do that operation for each line being read. 您将对要读取的每一line执行该操作。

So, finally, you will have: 所以,最后,你会:

def dict_from_file (file_name):
    file_pointer = open(file_name, 'r')
    data = file_pointer.readlines()
    print (data)
    output_dict = {}
    for line in data:
        l = line.split(',')
        output_dict[l[0]] = map(float, l[1:])
    file_pointer.close()
    return output_dict

#Main Program
result = dict_from_file ('stuff.txt')
print (result)

Running that code, will give you: 运行该代码,将为您提供:

{'Frank': [46.0, 83.0, 53.0, 79.0], 'Yohaan': [47.0, 77.0, 74.0, 96.0], 'Abigail': [84.0, 50.0, 72.0, 75.0], 'Mark': [90.0, 93.0, 60.0, 90.0]}

I suggest you use csv reader: 我建议你使用csv阅读器:

import csv
with open(file_name, 'rb') as csvfile:
    csv_reader = csv.reader(csvfile)
    for row in csv_reader:
        output_dict[row[0]] = [float(n) for n in row[1:]]

Something like that should work if correctly inserted into your for loop. 如果正确插入你的for循环,这样的东西应该工作。 I haven't tested the code, but it shouldn't be too far off. 我没有测试过代码,但它不应该太远。

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

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