2

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

And, the following code to read this data and create a Python dictionary:

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
            
k= users.keys()
print(k)

if 'Jane' in k:
    print('she is not in the dict')
if 'Jane ' in k:
    print('she *is* in the dict')

I see that there are trailing spaces in the keys:

dict_keys(['Jane ', 'Billy ', 'Jason ', 'Brian ', 'Laura ', 'Charlotte ', 'Christoper '])
she *is* in the dict

What is the best way to remove the spaces?

Thanks!

equanimity
  • 2,371
  • 3
  • 29
  • 53
  • 1
    Does this answer your question? [How do I trim whitespace?](https://stackoverflow.com/questions/1185524/how-do-i-trim-whitespace) – mkrieger1 Jan 01 '21 at 17:23

4 Answers4

3

try to change:

key, value = line.split('-')

to

key, value = [i.strip() for i in line.split('-')]
dimay
  • 2,768
  • 1
  • 13
  • 22
3

Change key, value = line.split('-') to key, value = line.split(' - ').

scenox
  • 698
  • 7
  • 17
1

You can replace this:

key, value = line.split('-')
users[key] = value

by this:

k=line.split('-')
users[k[0].strip()]=k[1]
IoaTzimas
  • 10,538
  • 2
  • 13
  • 30
1

Just change

users[key] = value

to

users[key.strip()] = value.strip()

This will generalize your code in case there is no space on either or both sides of '-' in split().

avio8
  • 82
  • 3