Create key/value pair in Python using an if conditional

Viewed 2785

In Python 3.5, is it possible to build a dictionary key/value pair using an if statement?

For example, given the following if-conditional:

if x == 1:
    color = 'blue'
elif x == 2:
    color = 'red'
else:
    color = 'purple'

How can I create a dictionary key/value pair that incorporates this if-conditional?

dict(
    number = 3,
    foo = 'bar',
    color = 'blue' if x == 1, 'red' if x == 2, else 'purple'
)
3 Answers
Related