Python:根据文件内容构建字典

Noa*_*oam 2 python dictionary list

假设我有一个名称和值的文件,其条目如下:

lasker:22,45,77,101
kramnik:45,22,15,105
Run Code Online (Sandbox Code Playgroud)

什么是Pythonic最方便的方法是将它们作为键输入字典,将值作为列表如下:

{ 'lasker': (22,45,77,101), 'kramnik': (45,22,15,105) }
Run Code Online (Sandbox Code Playgroud)

编辑

反正是按照我从文件中读取它们的顺序迭代它们还是需要不同的数据结构?

Joc*_*zel 13

我认为这段代码的工作方式非常清楚:

def get_entries( infile ):
    with open( infile, 'rt') as file:
        for line in file:
            name, nums = line.split(':', 1)
            yield name, tuple(int(x) for x in nums.split(','))

# dict takes a sequence of  `(key, value)` pairs and turns in into a dict
print dict(get_entries( infile ))
Run Code Online (Sandbox Code Playgroud)

编写生成对并将其传递给的生成器dict是一种非常有用的模式.

如果您只想迭代对,可以直接执行此操作:

for name, nums in get_entries( infile ):
    print name, nums
Run Code Online (Sandbox Code Playgroud)

但如果你需要字典的访问后,还命令你可以简单地替换dictOrderedDict:

from collections import OrderedDict
print OrderedDict(get_entries( infile ))
Run Code Online (Sandbox Code Playgroud)