Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create key/value pair in Python using an if conditional

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'
)
like image 568
enter_display_name_here Avatar asked Jan 02 '26 03:01

enter_display_name_here


2 Answers

The key must be a non-mutable (pronounced: "hash-able") object. This means a string, tuple, integer, float, or any object with a __hash__ method. The dictionary you are creating seems to need this:

x = 2
d1 = {
    "number": 3,
    "foo": "bar",
    "color": "blue" if x == 1 else "red" if x == 2 else "purple"
}
# or:
x = 3
d2 = dict(
    number=3,
    foo="bar",
    color="blue" if x == 1 else "red" if x == 2 else "purple"
)
print(d1["color"]) # => red
print(d2["color"]) # => purple

As @timgeb mentioed, the more generally preferred way is to use the dict.get method since longer if-conditional statements become less and less readable.

like image 199
Goodies Avatar answered Jan 03 '26 16:01

Goodies


I suggest not to use the conditional, but a mapping of numbers to colors instead.

>>> x = 2
>>> dict(
...     number = 3,
...     foo = 'bar',
...     color = {1: 'blue', 2: 'red'}.get(x, 'purple')
... )
{'color': 'red', 'foo': 'bar', 'number': 3}

If you have use for the number -> color mapping multiple times, define it outside and assign a name to it.

If x is not found in the dictionary, the fallback value 'purple' will be returned by get.

like image 44
timgeb Avatar answered Jan 03 '26 16:01

timgeb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!