1

I have the following code, and it works. I am checking if a JSON object has a full field and does not contain the underlying fields (Jira API, if you're interested). Is there a more concise way of writing the for loop?

myResponse = requests.get(url,auth=(urlUser,urlPass))

jd = myResponse.json()
myVals = jd['issues']

print(myVals[0].keys())
for issue in myVals:
    if issue['fields']['assignee'] is not None:
        assignee = issue['fields']['assignee']['displayName']
    else:
        assignee = "Unassigned"

1 Answer 1

3

You can use dict.get with fallback dictionary:

>>> issues = {'fields': {'assignee': None}}
>>> issues['fields']['assignee'] or {}  # fallback to an empty dictionary
{}
>>> (issues['fields']['assignee'] or {}).get('displayName', 'Unassigned')
'Unassigned'

for issue in myVals:
    assignee = (issue['fields']['assignee'] or {}).get('displayName', 'Unassigned')

OR define fallback dictionary like below:

UNASSIGNED = {'displayName': 'Unassigned'}
for issue in myVals:
    assignee = (issue['fields']['assignee'] or UNASSIGNED)['displayName']
Sign up to request clarification or add additional context in comments.

1 Comment

The following code worked perfectly. I'm assuming the two methods are a matter of preference? for issue in myVals: assignee = (issue['fields']['assignee'] or {}).get('displayName', 'Unassigned')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.