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!
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))
BTW, what we call dict comprehension is something like the following which is only available in 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}