Skip to main content

Python Cheat Sheet: Dictionaries

Python dictionaries are built on hash tables. They can hold arbitrary key-value pairs, and the keys and values don’t have to share a single data type. Dictionaries are unordered, meaning no ordering between elements is defined, so you can’t rely on any particular sequence when iterating over them.

Note: Unless stated otherwise, all examples use Python 2 syntax.

Creating an empty dictionary

D = {}

Initializing a dictionary

D = dict((i, False) for i in xrange(1, 11) if i % 2 == 0)   # Python 2
D = {i: False for i in range(1, 11) if i % 2 == 0}          # Python 3

Note: the second form is known as a dictionary comprehension.

Iterating over all items

for i in D:
    print i, D[i]   # key, value

Or alternatively:

for k, v in D.iteritems():
    print k, v      # key, value

Checking whether a key exists

if k in D:
    print k

Adding elements

D[key] = value

Note: if the key already exists, no error is raised; its value is simply overwritten.

Removing elements

del D[key]

Removing duplicates from a list with a dictionary as a lookup table

D = {}
unique = []
for i in L:
    if i not in D:
        D[i] = True
        unique.append(i)
L = unique

Note: this keeps the first occurrence of each element and preserves the original order. To modify the list in place instead of rebinding the name, use L[:] = unique as the last line.

A set is a better fit for this job. If the original order of the list doesn’t matter, you can use the shorter form list(set(L)).

That’s all for today. Thanks for reading!