Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
Counting elements with dictionary (kracekumar.com)
2 points by kracekumar on Feb 26, 2014 | hide | past | favorite | 1 comment


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.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: