Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this line work in this python script

Tags:

python

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.

like image 685
lgxjames Avatar asked Aug 31 '25 23:08

lgxjames


2 Answers

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.)

like image 172
Rafe Kettler Avatar answered Sep 03 '25 13:09

Rafe Kettler


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.

like image 24
Håvard Avatar answered Sep 03 '25 11:09

Håvard