Python nested understanding of dict

Can someone explain how to make nested dictations?

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

I would like:

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

Thank!

+3
source share
4 answers
dict((x+y,0) for x in 'cd' for y in 'ab')
+8
source

You can simplify this to one cycle 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}
>>> 
+4
source
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)}
+1

, 2 , 2 . , , .

>>> [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>]

,

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

.

mouad answer

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

Python 2.7 3.0 dict

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

Source: https://habr.com/ru/post/1784361/


All Articles