Reputation: 3163
I am trying to do the following operation.
rating = []
for i in result['search_results']:
rating.append(float(i['rating']) if i['rating'] exists else 'NaN')
The API call sometimes does not return this value. How can I do an append if exists logic in Python?
Upvotes: 1
Views: 329
Reputation: 56
You can use the get
method in a dictionary to retrieve a value if it exists and return a default value otherwise.
rating = []
for i in result['search_results']:
rating.append(float(i.get('rating', math.nan)))
Upvotes: 4