将文本文件中的键和值添加到词典中



我有一个文本文件test.txt,上面有两行:

1 "test one"
2 "test two"

我只想把这两行添加到test_dict:

test_dict = {} 
with open("test.txt", "r") as f: 
for line in f:
(key, val) = line.split()
test_dict[int(key)] = val
print(test_dict)

错误:

ValueError: too many values to unpack (expected 2)

预期结果:

test_dict = {1: "test one", 2: "test two"}

编辑问题后,这应该会起作用:

test_dict = {}
with open("testtt.txt", "r") as f:
for line in f:
(key, val) = line.split(maxsplit=1)
test_dict[int(key)] = val
print(test_dict)

因为我们需要第一项作为密钥;其余的";作为值,所以我将maxsplit=1作为参数传递给split()。这只将线从左侧分割了1次。

最新更新