Reputation: 2533
I have the following data in a text file named 'user_table.txt'
:
Jane - valentine4Me
Billy
Billy - slick987
Billy - monica1600Dress
Jason - jason4evER
Brian - briguy987321CT
Laura - 100LauraSmith
Charlotte - beutifulGIRL!
Christoper - chrisjohn
I'm trying to read this data into a Python dictionary using the following code:
users = {}
with open("user_table.txt", 'r') as file:
for line in file:
line = line.strip()
# if there is no password
if '-' in line == False:
continue
# otherwise read into a dictionary
else:
key, value = line.split('-')
users[key] = value
print(users)
I get the following error:
ValueError: not enough values to unpack (expected 2, got 1)
This most likely results because the first instance of Billy doesn't have a '-'
to split on.
If that's the case, what's the best way to work around this?
Thanks!
Upvotes: 0
Views: 63
Reputation: 4069
Your condition is wrong, must be:
for line in file:
line = line.strip()
# if there is no password
# if '-' not in line: <- another option
if ('-' in line) == False:
continue
# otherwise read into a dictionary
else:
key, value = line.split('-')
users[key] = value
or
for line in file:
line = line.strip()
# if there is password
if '-' in line:
key, value = line.split('-')
users[key] = value
Upvotes: 2