开发者

dictionary key error python

开发者 https://www.devze.com 2023-02-19 01:43 出处:网络
I get the error \"Key Error: \'tempMax\'\". Can anyone tell what the problem is with the following code:

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 < 开发者_如何学C15.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.


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'] = {}


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


The first line of your method

self.features.setdefault(cat,{f:{'high':0,'mid':0,'low':0}})

sets self.features[cat] to the given value only if it is not already set, and does nothing otherwise. In the latter case, it might happen (and obviously happens) that the dictionary self.features[cat] does not have the key f, so trying to access self.features[cat][f] will raise a KeyError.

0

精彩评论

暂无评论...
验证码 换一张
取 消