简体   繁体   中英

Generating a dict from a list of tuples using dict() builtin

I was surprised that both examples in the code block below return the same value. How does the dict() builtin accept the second syntax (the one that is not a generator expression)? Is this handled by the parser?

>>> words = ['cat','dog','frog']
>>> dict([(word, True) for word in words])
{'dog': True, 'frog': True, 'cat': True}
>>> dict((word, True) for word in words)
{'dog': True, 'frog': True, 'cat': True}

The second syntax is, in fact, a generator expression.

See PEP-289 . It even includes the following example:

d = dict( (k, func(k)) for k in keylist)

which is almost exactly what you've got.

The first syntax is a list comprehension , a somewhat similar but distinct construct.

One key difference as applied to your example is that the first version creates and discards a temporary list, whereas the second doesn't.

Both examples are iterables , so you could write it "long-hand" the same way:

Generator :

generator_construct = ((word, True) for word in words)
d = {}
for key, value in generator_construct:
    d[key] = value

List comprehension :

list_construct = [(word, True) for word in words]
d = {}
for key, value in list_construct:
    d[key] = value

Both can be iterated the same way. The only difference is the list comprehension builds a real list, and the generator yields values one at a time. For a large number of items, the list comprehension will have more overhead because of the extra storage.

A third option given as comment by @JonClements:

d = dict.fromkeys(words, True)

Of the two, this is closest to the generator in that it doesn't build a key/value list, but it works directly over the words iterable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM