Does there exist a way in Python 2.7+ to make something like the following?
{ something_if_true if condition else something_if_false for key, value in dict_.items() }
I know you can make anything with just ‘if’:
{ something_if_true for key, value in dict_.items() if condition}
You’ve already got it:
A if test else Bis a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:The final
ifclause acts as a filter, which is different from having the conditional expression.