简体   繁体   中英

Reading (somewhat) unstructured data from a text file to create Python Dictionary

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!

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM