我正在寻找一种在字典中使用 if else 条件来为键设置值的方法。有办法吗?
下面的例子可能会帮助你理解我想要做什么。这不是一个函数式 Python 代码。只是一个例子给你一个想法。
age = 22
di = {
'name': 'xyz',
if age>=18:
'access_grant': 'yes',
else:
'access_grant': 'no',
}
我认为这将是使用三元表达式的绝佳机会(Python也称其为“三元运算符”):
...
di = {
'name': 'xyz',
'access_grant': 'yes' if age >= 18 else 'no',
}
...
您可以使用函数将逻辑与字典分开:
def access_grant(age):
return 'yes' if age >= 18 else 'no'
age = 22
di = {
'name': 'xyz',
'access_grant': access_grant(age),
}
将逻辑置于字典之外可以更轻松地测试和重用。
在初始定义中设置尽可能多的项目,然后添加其他项目:
age = 22
di = {
'name': 'xyz',
... other known keys here
}
if age>=18:
di['access_grant'] = 'yes'
else:
di['access_grant'] = 'no'