(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)}
Not only do list and dictionary comprehensions make code more concise and easier to read, they are also faster than traditional for-loops.
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.
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.
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.
{ str(x):(x if x % 2 else x*10) for x in range(10) }
seems to work well
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With