How to add or increment a dictionary entry?

I did some time comparisons. Pretty much equal. The one-lined .get() command is fastest, though.

Output:

get 0.543551800627
exception 0.587318710994
haskey 0.598421703081

Code:

import timeit
import random

RANDLIST = [random.randint(0, 1000) for i in range(10000)]

def get():
    foo = {}
    for bar in RANDLIST:
        foo[bar] = foo.get(bar, 0) + 1


def exception():
    foo = {}
    for bar in RANDLIST:
        try:
            foo[bar] += 1
        except KeyError:
            foo[bar] = 1


def haskey():
    foo = {}
    for bar in RANDLIST:
        if foo.has_key(bar):
            foo[bar] += 1
        else:
            foo[bar] = 1


def main():
    print 'get', timeit.timeit('get()', 'from __main__ import get', number=100)
    print 'exception', timeit.timeit('exception()', 'from __main__ import exception', number=100)
    print 'haskey', timeit.timeit('haskey()', 'from __main__ import haskey', number=100)


if __name__ == '__main__':
    main()

The dict's get() method takes an optional second parameter that can be used to provide a default value if the requested key is not found:

foo[bar] = foo.get(bar, 0) + 1

You can also take advantage of the control structure in exception handling. A KeyError exception is thrown by a dictionary when you try to assign a value to a non-existent key:

my_dict = {}
try:
    my_dict['a'] += 1
except KeyError, err:    # in 2.6: `except KeyError as err:`
    my_dict['a'] = 1

Use a defaultdict:

from collections import defaultdict

foo = defaultdict(int)
foo[bar] += 1

In Python >= 2.7, you also have a separate Counter class for these purposes. For Python 2.5 and 2.6, you can use its backported version.

Tags:

Python

Syntax