0

Is it possible to iterate the list in side the dictionary? Looks like a complex syntax.

URLS = ['http://www.foxnews.com/',
    'http://www.cnn.com/',
    'http://europe.wsj.com/',
    'http://www.bbc.co.uk/',
    'http://some-made-up-domain.com/']

future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Bee..
  • 195
  • 1
  • 8

1 Answers1

3

You are looking at a dictionary comprehension; it builds a dictionary from a loop.

It is equivalent to:

future_to_url = {}
for url in URLS:
    future_to_url[executor.submit(load_url, url, 60)] = url

but spelt more succinctly.

The same can be done to produce a list:

[executor.submit(load_url, url, 60) for url in URLS]

or sets:

{executor.submit(load_url, url, 60) for url in URLS}

or produce the elements lazily in a generator expression:

(executor.submit(load_url, url, 60) for url in URLS)

See the List Comprehensions section of the Python tutorial, and onwards, where the other comprehensions are explained.

Dict comprehensions require Python 2.7 or newer; if you need to port this back to older Python versions, you'd use the generator expression syntax inside a dict() function to produce (key, value) tuples:

dict((executor.submit(load_url, url, 60), url) for url in URLS)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343