-1

I'm just trying to understand the "keys =" line of code in the following script. This script was pulled in an answer linked below. I would just comment on that section but I don't have enough points to comment.

Search Multiple Strings (from File) in a file and print the line

I am having a hard time finding documentation on what "key for key" is. From what I found, it is part of the dictionary but any help in understanding that part would be greatly appreciated. Thanks!

keyfile = "keys.txt"
testfile = "test.txt"

keys = [key for key in (line.strip() for line in open(keyfile)) if key]

with open(testfile) as f:
for line in f:
    for key in keys:
        if key in line:
            print(line, end='')
            break
jonrsharpe
  • 107,083
  • 22
  • 201
  • 376
Mike
  • 13
  • 3

2 Answers2

0
keys = [key for key in (line.strip() for line in open(keyfile)) if key]

is called a list comprehension (which nests a generator comprehension)

The inner one reads a file line by line, and removes spaces & linefeed.

The outer one iterates on that inner one, and only issues the value if it's not empty.

To sum it up, it creates a list of non-empty lines of a file, very efficiently because the inner generator comprehension doesn't create an actual list, its values are evaluated when iterated upon.

Jean-François Fabre
  • 131,796
  • 23
  • 122
  • 195
0

key for key is only as x for x would be, so key as a variable will have the values of the elements of what follows the in keyword. The entire line means: list of all the elements (lines from the file) without linefeed (strip) where the element is not empty.

quantummind
  • 2,053
  • 1
  • 12
  • 19