Default Dict
By Maxime Biais, Saturday 6 January 2007 at 09:45 :: Python :: #2 :: rss
Bored to write 4 lines of code when you can write only one ? Yes, me too. I don't like the following code, when my fingers type this kind of code, my brain tell me "That's obvious I want to do that, I shouldn't write it".
d = {"chicken": 1, "rabbits": 2} l = ["chicken", "capcat"] for i in l: if not i in d: d[i] = 1 else: d[i] += 1The following class appease a part of my mind.
class DefaultDict(dict): "Dictionary with a default value for key that does not exist" def __init__(self, default, iterable_init=[], **kwds): super(DefaultDict, self).__init__(iterable_init) self.update(kwds) self.default = default def __getitem__(self, key): return self.get(key, self.default) def __copy__(self): return DefaultDict(self.default, self)Usage:
d = DefaultDict(0) d["capcat"] += 1



Comments
1. Sunday 28 January 2007 at 18:50, by paddy3118
2. Sunday 28 January 2007 at 19:54, by maxime
Write your comment