3

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!

4 Answers 4

8
dict((x+y,0) for x in 'cd' for y in 'ab')
Sign up to request clarification or add additional context in comments.

1 Comment

Great, I'm glad this can be simplified.
4

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}
>>> 

Comments

1
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)}

Comments

1

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}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.