从文件制作字典,第一个单词是每行中的键,然后其他四个数字是元组值

时间:2013-07-16 17:59:54

标签: python file dictionary tuples

这本字典应该采用一个国家的三个字母的国家代码,即英国的GRE,然后将其后的四个连续数字作为元组。它应该是这样的: {GRE:(204,203,112,116)}并继续为列表中的每个国家/地区执行此操作。 txt文件如下所示:

Country,Games,Gold,Silver,Bronze
AFG,13,0,0,2
ALG,15,5,2,8
ARG,40,18,24,28
ARM,10,1,2,9
ANZ,2,3,4,5 etc.;  

这实际上不是代码,我只想表明它是格式化的。 我需要我的程序跳过第一行,因为它是一个标题。这是我的代码到目前为止的样子:

def medals(goldMedals):
    infile = open(goldMedals, 'r')
    medalDict = {}
    for line in infile:
        if infile[line] != 0:
            key = line[0:3]
            value = line[3:].split(',')
            medalDict[key] = value
    print(medalDict)
    infile.close()
    return medalDict

medals('GoldMedals.txt')

4 个答案:

答案 0 :(得分:0)

with open('path/to/file') as infile:
    answer = {}
    for line in infile:
        k,v = line.strip().split(',',1)
        answer[k] = tuple(int(i) for i in v.split(','))

答案 1 :(得分:0)

你的for循环应该是:

next(infile)  # Skip the first line
for line in infile:
    words = line.split(',')
    medalDict[words[0]] = tuple(map(int, words[1:]))

答案 2 :(得分:0)

主题的变体,我将所有剩余的cols转换为int,我使用namedtuple

from collections import namedtuple

with open('file.txt') as fin:
    # The first line names the columns
    lines = iter(fin)
    columns = lines.next().strip().split(',')
    row = namedtuple('Row', columns[1:])
    results = {}
    for line in lines:
        columns = line.strip().split(',')
        results[columns[0]] = row(*(int(c) for c in columns[1:]))

# Results is now a dict to named tuples

这有一个很好的功能:1)跳过第一行,2)提供对行的偏移和命名访问:

# These both work to return the 'Games' column
results['ALG'].Games
results['ALG'][0]

答案 3 :(得分:0)

我认为督察G4dget的答案是最具可读性的......但对于那些打码高尔夫的人来说:

with open('medals.txt', 'r') as infile:
    headers = infile.readline()
    dict([(i[0], tuple(i[1:])) for i in [list(line.strip().split(',')) for line in infile]])