mchd
mchd

Reputation: 3163

How to do "append if exists" in Python?

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

Answers (1)

SG31
SG31

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

Related Questions