0

I have this textfile.txt:

i
car
air
me

And a dictionary is defined as:

dictionary = {"me":3, "you":4, "else": 10, "i":2}

I'm looking for a way to delete the words in textfile.txt from the dictionary in a generalizable way (I'm using a loop here) My attempt:

words_to_delete = open("textfile.txt", "r")
for i in words_to_delete.readlines():
    del dictionary[i]

# Output: KeyError: 'i\n'

Going further, I think is because of this:

for i in words_to_delete.readlines():
    print(i == "me")

# Output: False, False, False, False

Why the values from the loop are not comparable from the textfile.txt?

If I run this:

for i in words_to_delete.readlines():
    print(type(i))

<class 'str'>
<class 'str'>
<class 'str'>
<class 'str'>

It's a string, so why the strings i and me from the dictionary returns False when comparing it with brute-force written strings?

Arya McCarthy
  • 8,554
  • 4
  • 34
  • 56
Chris
  • 2,019
  • 5
  • 22
  • 67

1 Answers1

1

You need to trim the whitespaces (or in this case \n which is a newline. Call the strip method on the strings that have \n at the end. (like s.strip())

DownloadPizza
  • 3,307
  • 1
  • 12
  • 27