Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to strip trailing space from keys in a Python Dictionary?

Tags:

python

io

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!

like image 738
equanimity Avatar asked Mar 26 '26 21:03

equanimity


2 Answers

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

like image 157
scenox Avatar answered Mar 28 '26 10:03

scenox


try to change:

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

to

key, value = [i.strip() for i in line.split('-')]
like image 44
dimay Avatar answered Mar 28 '26 12:03

dimay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!