Informatics Practices · Ch 4 — Working with Lists and Dictionaries
Accessing Items in a Dictionary
Accessing Items in a Dictionary
Sequences — strings, lists and tuples — hand out their elements through indexing: you ask for position 0, 1, 2 and so on. A dictionary works on a different principle. Its items are reached via the keys, not via relative positions. Each key serves as the index of the dictionary, and each key maps to its value — so instead of asking "what is at position 2?", you ask "what value belongs to this key?".
The syntax mirrors list indexing, but with the key inside the square brackets:
>>> dict3 = {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}
>>> dict3['Ram']
89
>>> dict3['Sangeeta']
85
dict3['Ram'] returns 89 because the key 'Ram' maps to the value 89; dict3['Sangeeta'] returns 85 for the same reason. The binding between a key and its value is fixed by the dictionary's contents, not by where the item sits: 'Ram' always maps to 89 and 'Sangeeta' always maps to 85 regardless of which position their items occupy. In that sense, for retrieving a value the order of items does not matter — only the key does.
Looking up a key that the dictionary does not contain is an error. Asking for an unspecified key raises a KeyError:
>>> dict3['Shyam']
KeyError: 'Shyam'
``` …