如何将文本放入具有多个值的键的字典中?

时间:2016-03-17 20:58:39

标签: python-3.x dictionary text-files

我的文本文件如下所示:

詹姆斯,10岁,7岁,9岁。

Liz,4,6,3

鲍勃,8岁,2岁,5岁

我必须将这些放入字典中,其中每个名称都是关键,三个分数是值。 如何只创建一个字典并将数据添加到其中。 字典应如下所示:

{'詹姆斯':[10,7,9],' Liz':[4,6,3],' Bob':[8, 2,5]}

目前我的代码看起来像这样:

打开(' Class-A.txt')为f:

    lines = f.readlines()[0:4]

    student1_dict = {}

    key = None

    for line in lines:

        line = line.strip()

        if not key:

            key = line

            student1_dict[key] = []

        else:

            student1_dict[key].append(line)

打印(student1_dict)

但是,它以奇怪的格式输出数据,因为它处理多个字典。 ?? 这是输出:

{' James,10,7,9':[' Liz,4,6,3',' Bob,8,2,5', '']}

2 个答案:

答案 0 :(得分:2)

您可以使用带有csv.reader的dict comp,使用python 3中的extended iterable unpacking来创建键/值配对:

from csv import reader

with open("in.csv") as f:
    dct = {k: list(map(int, rest)) for k,*rest in reader(f, skipinitialspace=1)}
    print(dct)

输出:

{'Bob': [8, 2, 5], 'Liz': [4, 6, 3], 'James': [10, 7, 9]}

您并不严格需要skipinitialspace,因为int可以处理空格,但是如果您想将值保留为字符串,则可以添加它,或者在数字之前有前导空格。< / p>

如果你要使用python2,语法会略有不同但仍然简洁,你只需要切片/索引:

from csv import reader

with open("in.csv") as f:
    dct = {row[0]: map(int,row[1:]) for row in reader(f, skipinitialspace=1)}

如果您有空行,则只需添加if row

dct = {row[0]: map(int,row[1:]) for row in reader(f, skipinitialspace=1) if row}

对于python3:

with open("in.csv") as f:
    rd =  reader(f, skipinitialspace=1)
    dct = {k: list(map(int, rest)) for k, *rest in filter(None, rd)}
    print(dct)

如果你想使用for循环逻辑是相同的,不需要多个循环,索引和切片是python中一个非常基本的任务:

from csv import reader

with open("in.csv") as f:
    dct = {}
    for row in reader(f, skipinitialspace=1):
        # if we have data
        if row:
            # index first element to get the key then
            # slice from the first element to the end casting to int
            dct[row[0]] = map(int,row[1:])
    print(dct)

python3代码可以按照相同的逻辑变成类似的东西。

答案 1 :(得分:1)

这是获得所需结果的一种方法。使用更紧凑的代码可以缩短和优化这一点,但这更容易逐步解释。

import csv # import the csv module to help us parse the text file


# Create an empty dictionary.
scoreDict = {}

# Open the text file to parse.
with open('sample.csv', newline='') as csvfile:
    # Return an iterable reader object
    reader = csv.reader(csvfile)

    # Now we iterate through the reader object.
    for row in reader:
        if row: # Ignore empty rows
            scoresList = [] # Create an empty list we will be adding scores to.
            # We use the enumerate here to keep track of where we are in the list.
            for index, column in enumerate(row):
                if index != 0: # Ignore the first column as we use it as a key                     
                    # Turn score into an integer and add it to a list.
                    scoresList.append(int(column)) 
                    # Add the list of scores to the dictionary.
                    scoreDict[row[0]] = scoresList 

print(scoreDict)

输出:

{'Liz': [4, 6, 3], 'Bob': [8, 2, 5], 'James': [10, 7, 9]}