在 Python 3.5 中,是否可以使用 if
语句构建字典键/值对?
例如,给定以下if-conditional
:
if x == 1:
color = 'blue'
elif x == 2:
color = 'red'
else:
color = 'purple'
如何创建包含此 if-conditional
的字典键/值对?
dict(
number = 3,
foo = 'bar',
color = 'blue' if x == 1, 'red' if x == 2, else 'purple'
)
最佳答案
键必须是一个不可改变的(读作:“hash-able”)对象。这意味着字符串、元组、整数、 float 或任何具有 __hash__
方法的对象。您正在创建的字典似乎需要这个:
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
正如@timgeb 提到的,更普遍的首选方法是使用 dict.get
方法,因为较长的 if 条件语句变得越来越不可读。
关于python - 使用 if 条件在 Python 中创建键/值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35962790/