2

In the following code snippet:

for record in records:    
  max = record.get_values()['max']

In this code, I am getting max value from record. "records" is a generator object here. The problem is, in some cases max field won't be present. So I am getting KeyError in those cases. I want to assign max = 0 if max isn't present in record. So far I have come with this solution:

try:    
  max = record.get_values()['max']
except:
  max = 0

But I want to avoid using try-except in this case as there are many more lines like this and it will make my code look messy. How can I achieve the same functionality without using try-except or long lines of code? It will be preferable if this can be done in a single line of code.

2
  • 2
    If record.get_values() returns a dictionary then you could use max = record.get_values().get("max", 0) Commented Nov 4, 2020 at 12:36
  • Thanks, it solves my problem. Commented Nov 4, 2020 at 13:16

2 Answers 2

4

you can use get() to avoid key error. it will return None for missing key: if record.get_values() returns a dict use:

for record in records:    
  max = record.get_values().get('max')


# will return **None** for missing key by default, you can add a default value if needed.

a simple example is:

emp_dict = {'Name': 'Pankaj', 'ID': 1}

emp_id = emp_dict.get('ID')
emp_role = emp_dict.get('Role')
emp_salary = emp_dict.get('Salary', 0)

print(f'Employee[ID:{emp_id}, Role:{emp_role}, Salary:{emp_salary}]')

# Output: Employee[ID:1, Role:None, Salary:0]
Sign up to request clarification or add additional context in comments.

3 Comments

Better is to supply a default in the get() call, as already commented.
.get takes a second argument to return if the key isn't present.
default value is optional. you can mention a default value as your wish but by default it will return None. check here if needed w3schools.com/python/ref_dictionary_get.asp
-1

You can check if the key "max" exists in the dictionary using a ternary operator.

max = record.get_values()["max"] if "max" in record.get_values().keys() else 0

Comments

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.