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.
source
share