简体   繁体   中英

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'
)

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.

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 .

Little addition. Solution with if-conditions may look more nice with some formatting (especially if you have many conditions):

x = 3
d1 = {
    "number": 3,
    "foo": "bar",
    "color": 
        "blue" if x == 1 else 
        "red" if x == 2 else 
        "purple"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM