Reputation: 163
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"
Upvotes: 1
Views: 2336
Reputation: 369474
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']
Upvotes: 3