KraftDiner wrote:
> Ok so this is nice.. Just one thing.. When you try to get a value from
> a dictionary
> and it isn't found in the dictionary things go bad...
> 
> Take this for example:
> 
> class histogram(object):
>       def __init__(self):
>               self.histo = {}
> 
>       def update(self, point):
>               if self.histo.get(point) != None:
>                       self.histo[point] = self.histo[point] + 1
>               else:
>                       self.histo[point] = 1
> 
>       def get(self, point):
>               return self.histo[point]
> 
> 
> hist = histogram()
> hist.update((0,0,0))
> hist.update((0,0,1))
> hist.update((0,0,1))
> hist.get((0,0,0))
> hist.get((0,0,1))
> hist.get((0,0,2))
> 
> spews out this error:
> 
> Traceback (most recent call last):
>   File "histogram.py", line 21, in ?
>     hist.get((0,0,2))
>   File "histogram.py", line 12, in get
>     return self.histo[point]
> KeyError: (0, 0, 2)
> 

Try this:

class histogram(object):
        def __init__(self):
                self.histo = {}

        def update(self, point):
                self.histo[point] = self.histo.get(point, 0) + 1

        def get(self, point):
                return self.histo.get(point, 0)

dict.get's default return value is your friend.

-Kirk McDonald
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to