dictionary key error python

15,064

Solution 1

The issue is in the setdefault call. f is set to tempMax but tempMax was never initialized. In this case it needs to be initialized as a dictionary because you have 'high' as a key

self.features[cat][f]['high']


self.features[cat]['tempMax'] = {}

If you come from a php background then this is a common mistake. In python you have to initialize your dictionaries. They have to be initialized at every nested level. Common way to do it is...

try:
   self.features[cat]
except KeyError, e:
   self.features[cat] = {}

try
   self.features[cat]['tempHigh']
except KeyError, e:
   self.features[cat]['tempHigh'] = {}

Solution 2

dict.setdefault() only sets the key once. If you pass 'tempMean' once then you will not get a chance to set tempMax.

Share:
15,064
sam
Author by

sam

Updated on June 25, 2022

Comments

  • sam
    sam almost 2 years

    I get the error "Key Error: 'tempMax'".

    Can anyone tell what the problem is with the following code:

    def catagorise(self, day, cat, f):
        self.features.setdefault(cat, {f:{'high':0,'mid':0,'low':0}})
    
        if f == 'tempMean':
            if day.tempMean > 15.0:
                self.features[cat][f]['high'] += 1
            elif day.tempMean > 8.0 and day.tempMean < 15.0:
                self.features[cat][f]['mid'] += 1
            elif day.tempMean <= 8.0:
                self.features[cat][f]['low'] += 1       
    
        if f == 'tempMax':
            if day.tempMax > 15.0:
                self.features[cat][f]['high'] += 1
            elif day.tempMax > 8.0 and day.tempMax < 15.0:
                self.features[cat][f]['mid'] += 1
            elif day.tempMax <= 8.0:
                self.features[cat][f]['low'] += 1   
    

    A day is an object which has variables such as mean temperature, max temperature etc. Cat is the category which it will be put into e.g 'Fog', 'Rain', 'Snow', 'None' and f is the feature to check e.g. 'tempMax'

    The features dictionary is defined when the class is created.