[Tutor] Addition, Dictionary, KeysError

Martin Walsh mwalsh at mwalsh.org
Sat Sep 13 23:06:39 CEST 2008


Martin Walsh wrote:
> Rilindo Foster wrote:
>> Scratch that, I'm a dork:
>>
>> OrderDict[(o[0])] = OrderDict.get(o[0],0) + float(o[1])
>>
>> http://www.faqts.com/knowledge_base/view.phtml/aid/4571/fid/541
>>
>> :D
>>
> 
> For this case you might also be interested in collections.defaultdict,
> added in python 2.5 I believe.
> 
> from collections import defaultdict
> 
> orders = defaultdict(float)
> orders[o[0]] += float(o[1])
> 
> HTH,
> Marty

It is so unlike me to respond without the obligatory doc reference:
http://docs.python.org/lib/defaultdict-objects.html
http://docs.python.org/lib/defaultdict-examples.html

FWIW, you can also accomplish something similar by subclassing dict and
defining a __missing__ method (also added in 2.5). Something like this
(untested):

class OrderDict(dict):
    def __missing__(self, key):
        return 0.0

orders = OrderDict()
orders[o[0]] += float(o[1])

See http://docs.python.org/lib/typesmapping.html

Note that it doesn't actually update the dict with any access as
defaultdict would...

In [3]: orders = defaultdict(float)

In [4]: orders['somekey']
Out[4]: 0.0

In [5]: orders
Out[5]: defaultdict(<type 'float'>, {'somekey': 0.0})

In [6]: orders = OrderDict()

In [7]: orders['somekey']
Out[7]: 0.0

In [8]: orders
Out[8]: {}

HTH,
Marty



More information about the Tutor mailing list