简体   繁体   中英

Python nested dict comprehension

Can someone explain how to do nested dict comprehensions?

>> j = dict(((x+y,0) for x in 'cd') for y in 'ab')
>> {('ca', 0): ('da', 0), ('cb', 0): ('db', 0)}

I would have liked:

>> j
>> {'ca':0, 'cb':0, 'da':0, 'db':0}

Thanks!

dict((x+y,0) for x in 'cd' for y in 'ab')

You can simplify this to a single loop by using the cartesian product from itertools

>>> from itertools import product
>>> j=dict((x+y,0) for x,y in product('cd','ab'))
>>> j
{'cb': 0, 'ca': 0, 'db': 0, 'da': 0}
>>> 
dict((x+2*y, 0) for x in range(1,4,2) for y in range(15, 18, 2))

顺便说一句,我们称之为dict理解就像下面这样只有Python2.7 +才能提供:

{x+2*y:0 for x in range(1,4,2) for y in range(15, 18, 2)}

The extra parentheses in the question introduce another generator expression that yields 2 generators each yielding 2 tuples. The list comprehension below shows exactly what is happening.

>>> [w for w in (((x+y,0) for x in 'cd') for y in 'ab')]
[<generator object <genexpr> at 0x1ca5d70>, <generator object <genexpr> at 0x1ca5b90>]

A list comprehension instead of the generator expression shows what the generators above contain

>>> [w for w in ([(x+y,0) for x in 'cd'] for y in 'ab')]
[[('ca', 0), ('da', 0)], [('cb', 0), ('db', 0)]]

And that is why you were getting two key-value of pairs of tuples.

Why mouad's answer works

>>> [w for w in ((x+y,0) for x in 'cd' for y in 'ab')]
[('ca', 0), ('cb', 0), ('da', 0), ('db', 0)]

In Python 2.7 and 3.0 and above, you can use dict comprehensions

>>> j = {x+y:0 for x in 'cd' for y in 'ab'}
>>> j
{'cb': 0, 'ca': 0, 'db': 0, 'da': 0}

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