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)
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)
如果你的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)
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)