Hacker News new | ask | show | jobs
by dalke 4489 days ago
That was the Pythonic approach until 2006. With Python 2.5 the Pythonic solution was often to use defaultdict:

    >>> from collections import defaultdict
    >>> words = ['a', 'the', 'an', 'a', 'an', 'the']
    >>> d = defaultdict(int)
    >>> for word in words:
    ...     d[word] += 1
    ... 
    >>> d
    defaultdict(<type 'int'>, {'a': 2, 'the': 2, 'an': 2})

It's a bit more cumbersome, but the performance is better, and defaultdict(list)[key].append() is much better than setdefault(key, []).append(value).

In modern Python (starting with Python 2.7, released in 2010), the Pythonic solution is collections.Counter:

    >>> from collections import Counter
    >>> words = ['a', 'the', 'an', 'a', 'an', 'the']
    >>> Counter(words)
    Counter({'a': 2, 'the': 2, 'an': 2})
or dict(Counter(words)) if you want the result to return an actual dict instead of a Counter instance.