【发布时间】:2021-12-29 14:06:21
【问题描述】:
假设以下文本文件 (dict.txt) 有
1 2 3
aaa bbb ccc
字典应该是{1: aaa, 2: bbb, 3: ccc} 这样的
我做到了:
d = {}
with open("dict.txt") as f:
for line in f:
(key, val) = line.split()
d[int(key)] = val
print (d)
但它没有用。我认为是因为txt文件的结构。
【问题讨论】:
-
读取第一行并拆分。阅读第二行并拆分。然后:How do I convert two lists into a dictionary?
-
这是一个非常丑陋的文件格式定义。您确定不能更改文件的写入方式吗?
-
为什么不使用 JSON 或类似 INI 的配置文件?,有一个可用于 INI 格式的解析器:docs.python.org/3/library/configparser.html
-
with open("dict.txt") as f: d = dict(zip(map(int, next(f).split()), next(f).split())).
标签: python dictionary txt key-value-store