Pre-PEP: Dictionary accumulator methods

El Pitonero pitonero at gmail.com
Sat Mar 19 11:21:28 EST 2005


Raymond Hettinger wrote:
> Separating the two cases is essential.  Also, the wording should
contain strong
> cues that remind you of addition and of building a list.
>
> For the first, how about addup():
>
>     d = {}
>     for word in text.split():
>          d.addup(word)

import copy
class safedict(dict):
    def __init__(self, default=None):
        self.default = default
    def __getitem__(self, key):
        if not self.has_key(key):
            self[key] = copy.copy(self.default)
        return dict.__getitem__(self, key)

text = 'a b c b a'
words = text.split()
counts = safedict(0)
positions = safedict([])
for i, word  in enumerate(words):
    counts[word] += 1
    positions[word].append(i)

print counts, positions




More information about the Python-list mailing list