0

I need to loop through dictionary keys in the Enron dataset and check if string 'PRENTICE' is included in the keys and print the full key out.

I would approach it this way,

for string in enron_data.keys():
    if "PRENTICE" in string:
        value = string
print(value)

On Github I found however this solution, which of course also works:

values = [string for string in enron_data.keys() if "PRENTICE" in string]

What is the logic of this approach? Why is it in square brackets? When we write '[string' before the for loop, is this the same as in my case 'value = string' at the end?

Thank you very much for a clarification and apologies for a beginner questions.

Trgovec
  • 555
  • 3
  • 7
  • 16
  • 1
    This is a list comprehension, simplified, it's just a fancy and more concise way to describe simple for loop structures, there are many tutorials on the web, just ask your friend mr google. Now regarding your code, it will only print the latest encounter of `"PRENTICE"` while the list comprehension stores each encountered instance in a list. – meow Feb 10 '18 at 16:10
  • 1
    Your first approach will break with a `NameError` if no such key is found. – user2390182 Feb 10 '18 at 16:11

0 Answers0