As the title suggests, I'm trying to read a file into a dictionary in Python. The error I'm getting is "not enough values to unpack (expected 2, got 1)". I've gone through different posts with the same error but the suggested solutions haven't been working for me. My text file is formatted like:
яблоко: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
So this (adapted from answers I found on other posts) should work:
myDict = {}
with open("fruits.txt", "r") as file:
for line in file:
key, value = line.strip().split(":")
myDict[key] = value
print(myDict)
But it's throwing the aformentioned error. Any ideas as to why?
Thank you very much for reading.
Putting this in an answer as a follow up to my comment. Very likely you have lines in your file that don't have the separator. You can skip the bad lines like this
try:
key, value = line.strip().split(":")
myDict[key] = value
except ValueError:
continue # will just go to the next item in the loop
Try to add an encoding
to open function. This code worked for me:
myDict = {}
with open("fruits.txt", encoding='utf8') as file:
for line in file:
key, value = line.strip().split(":")
myDict[key] = value
print(myDict)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.