【问题标题】:Is there a Ternary Operator in pythonpython中是否有三元运算符
【发布时间】:2022-01-24 17:03:23
【问题描述】:

我正在尝试为 python 做一个类似三元的运算符来检查我的字典值是否存在然后使用它或者将其留空,例如在下面的代码中我想获取 creator 和 @987654323 的值@,如果值不存在,我希望它是'',如果有办法在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 django conditional-operator


【解决方案1】:

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

【讨论】:

  • 感谢您的帮助,我的 assigneenull,当我将其设置为此 "assignee": issue['fields']['assignee'].get("displayName","") 时,我收到此错误:'NoneType' object has no attribute 'get'
【解决方案2】:

您可以使用.get(…) [Django-doc] 尝试从字典中获取项目并在字典不包含给定键的情况下返回可选的默认值,因此您可以将其实现为:

"creator": issue<strong>.get(</strong>'fields'<strong>, {}).get(</strong>'creator'<strong>, {}).get(</strong>'displayName'<strong>, '')</strong>,

与其他项目相同。

【讨论】:

    【解决方案3】:

    如果你想使用像三元这样的东西 你可以说

    value = issue['fields']['creator']['displayName'] if issue['fields']['creator'] else ""
    

    【讨论】:

      猜你喜欢
      • 2012-08-08
      • 2021-10-06
      • 2013-04-19
      • 2012-06-02
      • 2019-10-08
      • 2012-02-06
      • 2013-02-06
      • 1970-01-01
      • 2013-12-19
      相关资源
      最近更新 更多