Misunderstanding Python dict

(Sorry, could not resist the pun!)

I wonder why this cannot be translated:

dict([(str(x),x) if x % 2 else (str(x),x*10) for x in range(10)])

into this more readable expression using a dict understanding:

{str(x):x if x % 2 else str(x):x*10 for x in range(10)}
+5
source share
3 answers
{ str(x):(x if x % 2 else x*10) for x in range(10) }

seems to work well

+8
source

The priority is set so that it if .. elsedoes not apply to the whole pair key:value: this is only part of the value. That means you want to:

{str(x): (x if x % 2 else x*10 for x in range(10))}

In the unlikely event that you need a different key calculation, as well as a different value, in some cases you will have to do it like this:

{(str(x) if x % 2 else repr(x)) : x if x % 2 else x * 10 }

which would be equivalent:

dict([(str(x),x) if x % 2 else (repr(x),x*10) for x in range(10)])

Or decide that an explicit loop is more readable than a single-line for something so complex.

+1
source

It seems like it's just a question or grouping of expressions properly:

# original
{str(x): (x if x % 2 else x*10) for x in range(10)}

# slightly more complex, allowing both key and value to have the ternary
{(str(x) if x % 3 else str(x+1)) : (x if x % 2 else x*10) for x in range(10)}
+1
source

All Articles