Informatics Practices · Ch 4 — Working with Lists and Dictionaries
Introduction to Dictionaries
Introduction to Dictionaries
A list answers the question "what is the element at position 3?" — but many real situations ask a different kind of question: "what are Mohan's marks?" or "what is the capital of Kerala?". Here the natural way to look something up is by a name, not by a position. Python's answer is the dictionary, a data type that falls under the category of mapping.
A dictionary is a mapping between a set of keys and a set of values: each key is connected to one value, and looking up the key gives back its value. One key together with its value is called an item — so a dictionary is best pictured as a collection of key-value pairs.
The notation reflects this pairing:
- within an item, the key is separated from its value by a colon (:) — as in
'Mohan': 95; - consecutive items are separated from one another by commas.
Two properties are worth fixing clearly at the outset:
- Access is by key. Instead of numbering the entries 0, 1, 2, … as a list does, a dictionary indexes its values by their keys. The key plays the role the index plays in a list. …