1

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?

1
  • float(i['rating']) if 'rating' in i else 'NaN' Commented Nov 13, 2022 at 14:24

1 Answer 1

4

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)))
Sign up to request clarification or add additional context in comments.

1 Comment

Nice solution, it saves a lot of code.

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.