Python Glossary Русский

all Python 3Tuples (tuple)term

Tuple as a dictionary key

usage

Tuples are hashable (if all their items are), so they can serve as dictionary keys. Lists cannot.

Syntax

d[tuple_key] = val

Immutability alone is not enough: (1, [2]) is a tuple, but the list inside makes it unhashable and the dict answers TypeError: unhashable type: 'list'. Inside a subscript the parentheses are optional — d[1, 2] and d[(1, 2)] are the same lookup — while order does matter, so (1, 2) and (2, 1) are two distinct keys.

Examples

coords = {(0, 0): 'origin', (1, 0): 'right', (0, 1): 'up'}
print(coords[(0, 0)])
# → 'origin'
grid = {}
for i in range(3):
    for j in range(3):
        grid[(i, j)] = i * 3 + j
print(grid[(2, 1)])
# → 7
try:
    d = {[1, 2]: 'list'}
except TypeError as e:
    print(e)
# → ? текст TypeError зависит от версии: 3.14 добавил «cannot use 'list' as a dict key»
pair_count = {}
pairs = [(1, 2), (3, 4), (1, 2)]
for p in pairs:
    pair_count[p] = pair_count.get(p, 0) + 1
print(pair_count)
# → {(1, 2): 2, (3, 4): 1}
print(hash((1, 2, 3)))
# → ? хеш кортежа: солится PYTHONHASHSEED и меняется от запуска

See also

Open in the full glossarydocs.python.orgReport an inaccuracy