简体   繁体   English

Python function 将文本文件读入字典

[英]Python function to read a text file into a dictionary

I have a text file that contain the following lines:我有一个包含以下行的文本文件:

103;1;2 103;1;2

103;6;2 103;6;2

Where the first item is the participant no., the second item is the lesson followed and the third item is the rate.其中第一项是参加人数,第二项是所学课程,第三项是费率。

I want to combine the ratings of certain lessons in a dictionary.我想将某些课程的评分合并到字典中。

This dictionary should have the participant number as key and a list of ratings belonging to that participant as value.该字典应将参与者编号作为键,并将属于该参与者的评级列表作为值。 There are 7 lessons in total.总共有7节课。 If the lesson is not taken, the rating in the list should be "NA".如果没有上课,列表中的评分应为“NA”。

So for the text file above, the function should return a dictionary as follows:所以对于上面的文本文件,function 应该返回一个字典,如下所示:

{'103': [2.0, 'NA', 'NA', 'NA', 'NA', 2.0, 'NA']} {'103':[2.0,'NA','NA','NA','NA',2.0,'NA']}

How do I need to do this?我需要怎么做?

I have made a function that splits the items the way I want and creates a dictionary with the right key:我制作了一个 function 以我想要的方式拆分项目并使用右键创建一个字典:

def ratings():

    dictionary = {}
    file = open("ratings.csv")
    for line in file:
        line = line.split(";")
        dictionary[line[0]] = []
    return dictionary

This code returns my dictionary as follows:此代码返回我的字典如下:

{'103': []} {'103':[]}

However, I do struggle with the value part of the dictionary I need to return, ie the list with ratings of each participant.但是,我确实在处理需要返回的字典的值部分,即每个参与者的评分列表。 How can I combine the ratings in one list and insert "NA" if there is a missing value.如果有缺失值,我如何将评级合并到一个列表中并插入“NA”。

The problem is here:问题在这里:

dictionary[line[0]] = []

You're telling Python that the value in that dictionary for the key 103 is [] which is empty.你告诉 Python 那个字典中键103的值是[]是空的。

You probably want something like:你可能想要这样的东西:

def ratings():
    dictionary = {}
    file = open("ratings.csv")
    for line in file:
        line = line.split(";")
        if line[0] in dictionary: # already have some data for the participant
            dictionary[line[0]][line[1] - 1] = line[2] # minus 1 because Python is zero-indexed
        else: # new participant
            dictionary[line[0]] = ['NA','NA','NA','NA','NA','NA','NA',]
            dictionary[line[0]][line[1] - 1] = line[2] # minus 1 because Python is zero-indexed
    return dictionary

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

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