简体   繁体   English

python 中是否有三元运算符

[英]Is there a Ternary Operator in python

I'm trying to do a ternary like operator for python to check if my dictionary value exist then use it or else leave it blank, for example in the code below I want to get the value of creator and assignee , if the value doesn't exist I want it to be '' if theres a way to use ternary operator in python?我正在尝试为 python 做一个类似于三元的运算符来检查我的字典值是否存在然后使用它或者将其留空,例如在下面的代码中我想获取creatorassignee的值,如果值不'如果在 python 中有使用三元运算符的方法,我希望它是''

Here's my code:这是我的代码:

        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

Ternary operators in python act as follows: python 中的三元运算符的作用如下:

condition = True
foo = 3.14 if condition else 0

But for your particular use case, you should consider using dict.get() .但是对于您的特定用例,您应该考虑使用dict.get() The first argument specifies what you are trying to access, and the second argument specifies a default return value if the key does not exist in the dictionary.第一个参数指定您要访问的内容,第二个参数指定字典中不存在该键的默认返回值。

some_dict = {'a' : 1}

foo = some_dict.get('a', '') # foo is 1
bar = some_dict.get('b', '') # bar is ''

You can use .get(…) [Django-doc] to try to fetch an item from a dictionary and return an optional default value in case the dictionary does not contain the given key, you thus can implement this as:您可以使用.get(…) [Django-doc]尝试从字典中获取项目并返回可选的默认值,以防字典不包含给定键,因此您可以将其实现为:

"creator": issue.get('fields', {}).get('creator', {}).get('displayName', ''),

the same with the other items.与其他项目相同。

if you want to use something like ternary then you can say如果你想使用三元之类的东西,那么你可以说

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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