2

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?

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
M.Izzat
  • 1,086
  • 4
  • 22
  • 50

3 Answers3

2

Ternary operators in python act as follows:

condition = True
foo = 3.14 if condition else 0

But for your particular use case, you should consider using 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 ''
MichVaz
  • 31
  • 1
  • Thanks for the assist, my `assignee` is `null`, when I do set it to this `"assignee": issue['fields']['assignee'].get("displayName","")` I get this error : `'NoneType' object has no attribute 'get'` – M.Izzat Dec 23 '21 at 19:49
0

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:

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

the same with the other items.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
0

if you want to use something like ternary then you can say

value = issue['fields']['creator']['displayName'] if issue['fields']['creator'] else ""
Atlas Bravoos
  • 360
  • 2
  • 12