如何将文件转换为字典?

Dar*_*ick 82 python dictionary file

我有一个包含两列的文件,即

1 a 
2 b 
3 c
Run Code Online (Sandbox Code Playgroud)

我希望将此文件读入字典,以便第1列是键,第2列是值,即

d = {1:'a', 2:'b', 3:'c'}
Run Code Online (Sandbox Code Playgroud)

文件很小,因此效率不是问题.

Vla*_*d H 138

d = {}
with open("file.txt") as f:
    for line in f:
       (key, val) = line.split()
       d[int(key)] = val
Run Code Online (Sandbox Code Playgroud)

  • 这里使用`with`来处理文件清理.当你离开块时(通过正常的执行流程或异常),文件将自动关闭.您可以在此处阅读有关Python中上下文管理器的更多信息:http://effbot.org/zone/python-with-statement.htm (12认同)
  • 在这里真的有必要吗?也许他想要数字是字符串? (2认同)

Ign*_*ams 14

这会将密钥保留为字符串:

with open('infile.txt') as f:
  d = dict(x.rstrip().split(None, 1) for x in f)
Run Code Online (Sandbox Code Playgroud)

  • 一个简单的`dict([f中的行的line.split()])就足够了。 (2认同)

wim*_*wim 7

如果你的python版本是2.7+,你也可以使用dict理解,如:

with open('infile.txt') as f:
  {int(k): v for line in f for (k, v) in (line.strip().split(None, 1),)}
Run Code Online (Sandbox Code Playgroud)


tok*_*and 5

def get_pair(line):
    key, sep, value = line.strip().partition(" ")
    return int(key), value

with open("file.txt") as fd:    
    d = dict(get_pair(line) for line in fd)
Run Code Online (Sandbox Code Playgroud)