How to solve KeyError for non existing dictionary key?

Question:

I am trying to append to dict if key in nested filter exists. But even if the key is not there looks like the code gets executed because it shows me KeyError error. So, I don’t want this code to be executed if useValueFromAnotherField is not in my dict. How can I fix it?

KeyError: ‘useValueFromAnotherField’

dictionary

${FILTERS}=    {'Manager ID': {"operatorId": 'equal to',  "targetValue":'test',"dataType": 'Text', "targetType": 'targetText'}, 
'Terminated': {"operatorId": 'equl to', "targetValue": 'True', "dataType": 'Boolean', "targetType": 'targetBoolean'}}```

code
def filter_value_from_another_field(self, pipeline, new_filter, source_field_id, filter_to_add):
    for source_field in filter_to_add.keys():
        if filter_to_add[source_field]["useValueFromAnotherField"]:
            for value in self.ssi_get_value_from_another_field(pipeline, source_field_id).json_path("$.data"):
                if value["descriptor"] == filter_to_add[source_field]["useValueFromAnotherField"]:
                    new_filter["useValueFromAnotherField"] = value
                    return new_filter
Asked By: oksa23

||

Answers:

As John mentioned, you could use a simple check for the presence of the key useValueFromAnotherField in the dict filter_to_add[source_field] and the solution should look like below:

def filter_value_from_another_field(self, pipeline, new_filter, source_field_id, filter_to_add):
    for source_field in filter_to_add.keys():
        if "useValueFromAnotherField" in filter_to_add[source_field]:
            if filter_to_add[source_field]["useValueFromAnotherField"]:
                for value in self.ssi_get_value_from_another_field(pipeline, source_field_id).json_path("$.data"):
                    if value["descriptor"] == filter_to_add[source_field]["useValueFromAnotherField"]:
                        new_filter["useValueFromAnotherField"] = value
                        return new_filter
Answered By: kkgarg
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.