[英]Add keys and values from a text file to a dictionary
I have a text file test.txt
with two lines on it:我有一个文本文件
test.txt
,上面有两行:
1 "test one"
2 "test two"
I just want to add those 2 lines to test_dict
:我只想将这两行添加到
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)
Error:错误:
ValueError: too many values to unpack (expected 2)
Expected result:预期结果:
test_dict = {1: "test one", 2: "test two"}
Your code above should work, so your main issue may be that you have a different text file to what you attached.您上面的代码应该可以工作,因此您的主要问题可能是您的文本文件与附加的文件不同。
For example, if I change test.txt
to the following:例如,如果我将
test.txt
更改为以下内容:
1 test_one
2 test_two a
I get the same error as seen in your original question.我得到了与您原来的问题中看到的相同的错误。
One solution to this, if you're using an unknown input, is to use the index of the array instead of trying to unpack it into separate variables.如果您使用未知输入,对此的一种解决方案是使用数组的索引,而不是尝试将其解压缩到单独的变量中。 Therefore, if you have more than 2 pieces of data on a line, it'll run while ignoring the seperate errors:
因此,如果一行中有超过 2 条数据,它将在忽略单独错误的情况下运行:
test_dict = {}
# Open the file
with open("test.txt", "r") as file:
# Return an iterable of each line of the file
lines = file.readlines()
# Iterate through the lines
for line in lines:
# Split the line using the ' ' (space) character
result = line.split(' ')
# Set the value in the dictionary to the value
test_dict[int(result[0])] = result[1]
print(test_dict)
If, instead you want to incorporate error handling, you can check the length of the line, and print out an error message.相反,如果您想要合并错误处理,您可以检查行的长度,并打印出错误消息。 eg:
例如:
test_dict = {}
# Open the file
with open("test.txt", "r") as file:
# Return an iterable of each line of the file
lines = file.readlines()
# Iterate through the lines
for no, line in enumerate(lines):
# Split the line using the ' ' (space) character
result = line.split(' ')
if len(result) != 2:
# ERROR!
print(f"Line {no+1}: '{line}' has an invalid number of elements")
else:
# Set the value in the dictionary to the value
test_dict[int(result[0])] = result[1]
print(test_dict)
This outputs:这输出:
Line 2: '2 test_two a' has an invalid number of elements
{1: 'test_one\n'}
And, as you can see, it ignores the line with an error.而且,如您所见,它会忽略错误行。
After you edited your question, this should work:编辑问题后,这应该可以工作:
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)
Because we need the first item as a key, and "rest of them" as value, so I pass maxsplit=1
as an argument to split()
.因为我们需要第一项作为键,而“其余的”作为值,所以我将
maxsplit=1
作为参数传递给split()
。 This only split the line only 1 time from the left.这仅从左侧拆分线 1 次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.