【发布时间】:2020-11-11 14:21:44
【问题描述】:
正如标题所示,我正在尝试用 Python 将文件读入字典。我得到的错误是“没有足够的值来解包(预期 2,得到 1)”。我浏览了不同的帖子,但出现了相同的错误,但建议的解决方案对我不起作用。 我的文本文件格式如下:
яблоко:the round fruit of a tree of the rose family, which typically has thin red or green skin and crisp flesh. Many varieties have been developed as dessert or cooking fruit or for making cider
банан:a long curved fruit which grows in clusters and has soft pulpy flesh and yellow skin when ripe
вишня:a small, round stone fruit that is typically bright or dark red
所以这个(改编自我在其他帖子上找到的答案)应该可以工作:
myDict = {}
with open("fruits.txt", "r") as file:
for line in file:
key, value = line.strip().split(":")
myDict[key] = value
print(myDict)
但它抛出了上述错误。关于为什么的任何想法?
非常感谢您的阅读。
【问题讨论】:
-
您的文件中可能有一行没有“:”来分隔它。它可能是一个空行。您可以使用
try ... except ValueError让您跳过坏行。
标签: python file dictionary