Skip to content

Computer Science · Ch 10 — Tuples and Dictionaries

Accessing Items in a Dictionary

10.7.2

Accessing Items in a Dictionary

Sequences — strings, lists and tuples — are accessed by indexing: you ask for the item at a numbered position. Dictionaries work differently. The items of a dictionary are accessed via their keys, not via relative positions or indices. Each key serves as the index and maps to its value.

Putting the key in square brackets after the dictionary's name returns the value paired with that key:

>>> marks = {'Anita': 95, 'Bala': 89, 'Chetan': 92, 'Divya': 85}

>>> marks['Bala']
89
>>> marks['Divya']
85

A given key always maps to its own value — 'Bala' always yields 89 and 'Divya' always yields 85 — so the order of the items does not matter for lookup; only the key does.

When the key does not exist — KeyError

If you ask for a key that is not present in the dictionary, Python raises a KeyError: