我正在尝试为python做一个三元运算符来检查我的字典值是否存在然后使用它或者将其留空,例如在下面的代码中我想获取 creator
的值和assignee
,如果该值不存在,我希望它是 ''
python 中是否有使用三元运算符的方法?
这是我的代码:
in_progress_response = requests.request("GET", url, headers=headers, auth=auth).json()
issue_list = []
for issue in in_progress_response['issues'] :
# return HttpResponse( json.dumps( issue['fields']['creator']['displayName'] ) )
issue_list.append(
{
"id": issue['id'],
"key": issue['key'],
# DOESN'T WORK
"creator": issue['fields']['creator']['displayName'] ? '',
"is_creator_active": issue['fields']['creator']['active'] ? '',
"assignee": issue['fields']['assignee']['displayName'] ? '',
"is_assignee_active": issue['fields']['assignee']['active'] ? '',
"updated": issue['fields']['updated'],
}
)
return issue_list
最佳答案
Python中的三元运算符的作用如下:
condition = True
foo = 3.14 if condition else 0
但是对于您的特定用例,您应该考虑使用dict.get()
。第一个参数指定您要尝试访问的内容,第二个参数指定如果字典中不存在该键则默认返回值。
some_dict = {'a' : 1}
foo = some_dict.get('a', '') # foo is 1
bar = some_dict.get('b', '') # bar is ''
关于python - python中有三元运算符吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70466548/