Reputation: 53
I'm trying to extract lines from a text file, and make them keys for a new dictionary. So far, I've done this:
file = open(FileName, 'r')
dictionary = {}
for line in file:
if line == ("Red" or "Yellow" or "Blue"):
dictionary[line] = '' # And then I'll edit this empty string later.
return dictionary
file.close()
I feel like the "if line == ..." part isn't correct, or maybe I haven't read the file correctly? It isn't working.
Can someone point me in the right direction, without giving a straight answer? Thank you for reading through this! I appreciate it.
Upvotes: 2
Views: 7826
Reputation: 22953
Your feelings are correct. You see, Python's if statements do not work like an English setence. The second part of your if statement: ("Red" or "Yellow" or "Blue")
, is a boolean expression. The or
operator takes two values, and returns the first value which is true. In this case, since any non-empty string in Python is considered true in boolean terms, then your boolean expression returns "Red". This means that what your if statement is really saying is:
if line == "Red":
What you need to do is test line
against each value. While this could be done by going through each value and saying: if line == "Red" or line == "Blue"...
, Python was a much better way. Using the in
operator you can create an iterable with all the values you want to test line
against. Python will then test if line
is equal to any value in the iterable. In your case, using a tuple will be fine, but if you need to test line
against many more values, you should use a set()
instead:
if line in ("Red", "Yellow", "Blue"):
# do stuff
One last point is that line
could contain a newline. You can remove the newline by using .strip()
. So your finally solution would be:
if line.strip('\n') in ("Red", "Yellow", "Blue"):
# do stuff
Upvotes: 4
Reputation: 19806
Use:
if line in ("Red", "Yellow", "Blue"):
To check that your line does not contain spaces or \n
, you can use:
line.strip('\n ')
instead of just line
:
if line.strip('\n ') in ("Red", "Yellow", "Blue"):
dictionary[line.strip('\n ')] = ''
Upvotes: 2