unintuitive dict timings
Dave Benjamin
ramen at lackingtalent.com
Sun Oct 12 20:32:25 EDT 2003
In article <3f89e8bf$1_1 at dns.sd54.bc.ca>, Bob van der Poel wrote:
>
> Alex Martelli wrote:
>
>>
>> def sede(key, val):
>> d.setdefault(key, []).append(val)
>>
>> appears to be very marginally fastest, but again it's a close call:
>
> Ahhh, an example of setdefault(). I looked at this in the docs but it
> really didn't make much sense.... I'll give this a try just to see what
> difference it makes.
Another solution would be to subclass dict to make a dictionary that
automatically creates lists as needed. For example:
class dict_of_lists(dict):
def __getitem__(self, key):
try:
return dict.__getitem__(self, key)
except KeyError:
self[key] = []
return self[key]
dol = dict_of_lists()
dol['a'].append(1)
dol['b'].append(2)
dol['c'].append(3)
dol['c'].append(4)
dol['c'].append(5)
print dol
Output: {'a': [1], 'c': [3, 4, 5], 'b': [2]}
--
.:[ dave benjamin (ramenboy) -:- www.ramenfest.com -:- www.3dex.com ]:.
: d r i n k i n g l i f e o u t o f t h e c o n t a i n e r :
More information about the Python-list
mailing list