Reputation: 73
food = dict(line.split(":", 1) for line in open("file") if line.strip())
I know what this code does but I don't understand why it was put together like this, So can someone explain to me the logic of adding the "if" statement at the end.
How does telling the script to make a dictionary using iteration from a file work, then just adding
if line.strip()
work? doesn't something need to go after that statement?? What is it telling the script since there is no condition after it?
I know this code works because I tried it but I'm baffled at HOW it works.
Upvotes: 4
Views: 3033
Reputation: 76955
The if statement is a filter for the generator expression. At the end of a generator expression, you can have an if statement to specify conditions that each item needs to meet to be included in the final generator.
You might better understand a more simple example:
(i for i in range(100) if i % 3 == 0)
returns a generator that contains every number from 0 to 99 that is divisible by 3.
In your particular example, the if line.strip()
filters the final generator to only strings where line.strip()
is True (the idea is probably to make sure that there is some content in each string other than whitespace).
(If you don't know what generators are, see this.)
Upvotes: 6
Reputation: 129001
This uses the list comprehension syntax (or to be more precise, in this case, it's a generator comprehension). It goes a little like this:
<expression> for <name> in <iterable>[ if <condition>]
For each item in iterable
, it will set name
to that item and evaluate expression
, but only if condition
is truthy.
So what it does: It iterates over the lines in a file. If the line is empty, it skips it. If the line is not empty, it will split it on a colon with a maximum of two items. After it has iterated over everything, it will turn it into a dict
.
Upvotes: 1
Reputation: 10080
if line.strip()
simply checks that the string is not empty or space-only. Adding the if-statement to the end is simply how the syntax for generator expressions work; when iterating the lines in the file, the lines where the if-statement is false are excluded.
Upvotes: 2
Reputation: 33397
It's a comprehension.
Adding a trailing if
will check for each element if it is valid whithin your condition and add it to a list (in your case, a generator)
>>> [i for i in range(10) if i%2]
[1, 3, 5, 7, 9]
And you got only odd numbers
Upvotes: 1