Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dict incomprehension

(Sorry, couldn't resist the pun!)

I wonder why it doesn't seem possible to translate:

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

into this more readable expression, using dict comprehension:

{str(x):x if x % 2 else str(x):x*10 for x in range(10)}
like image 806
cjauvin Avatar asked Aug 30 '12 15:08

cjauvin


People also ask

Are dictionary comprehensions faster?

Not only do list and dictionary comprehensions make code more concise and easier to read, they are also faster than traditional for-loops.

How do you check if a key exists in a dictionary Python?

Check If Key Exists Using has_key() The has_key() method is a built-in method in Python that returns true if the dict contains the given key, and returns false if it isn't.

Can you do dictionary comprehension in Python?

Dictionary comprehension is a method for transforming one dictionary into another dictionary. During this transformation, items within the original dictionary can be conditionally included in the new dictionary and each item can be transformed as needed.

How do you sort a dictionary by value in Python?

To correctly sort a dictionary by value with the sorted() method, you will have to do the following: pass the dictionary to the sorted() method as the first value. use the items() method on the dictionary to retrieve its keys and values. write a lambda function to get the values retrieved with the item() method.


2 Answers

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

seems to work well

like image 113
georg Avatar answered Oct 28 '22 18:10

georg


The precedence is set so that the if .. else doesn't apply to the whole key:value pair: it is only part of the value. That means you want:

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

In the unlikely event that you wanted a different key calculation, as well as a different value, in some cases, you would 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 to:

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 one-liner for something so complex.

like image 29
lvc Avatar answered Oct 28 '22 18:10

lvc