Informatics Practices · Ch 3 — Brief Overview of Python
Mapping
Mapping
Sequences store items by position; a mapping stores items by name. Mapping is an unordered data type in Python — its items are not kept at numbered positions the way string, list and tuple elements are, so there is no "first" or "third" element to speak of. Currently, Python has only one standard mapping data type, called the Dictionary.
A dictionary in Python holds data items as key-value pairs. The idea mirrors an ordinary language dictionary: you look up a word (the key) to find its meaning (the value). The essentials of how a dictionary is written and used:
- The items are enclosed in curly brackets { }.
- Every key is separated from its value by a colon (:) sign, giving pairs of the form key : value.
- The pairs of a dictionary are accessed using the key — you ask for a key, and the dictionary hands back the value stored against it.
- Keys are usually of string type, while their values can be of any data type.
- To access any value in the dictionary, specify its key in square brackets [ ].
One practical property makes dictionaries attractive: they permit faster access to data. Instead of scanning through a collection position by position looking for what you want, you go straight to the value by naming its key.
The chapter's example builds a small dictionary describing a fruit and then retrieves one value from it:
#create a dictionary
>>> dict1 = {'Fruit':'Apple', 'Climate':'Cold', 'Price(kg)':120}
>>> print(dict1)
{'Fruit': 'Apple', 'Climate': 'Cold', 'Price(kg)': 120}
#getting value by specifying a key
>>> print(dict1['Price(kg)'])
120
Read the structure carefully. dict1 holds three key-value pairs: the key 'Fruit' maps to the value 'Apple', 'Climate' maps to 'Cold', and 'Price(kg)' maps to 120. All three keys are strings, exactly the usual practice, while the values mix types — two strings and a number — which is perfectly legal, since values can be of any data type. The retrieval line shows the access rule in action: writing the key 'Price(kg)' inside square brackets after the dictionary's name fetches the value stored against that key, and 120 is printed.
Square brackets do double duty in Python, and the meaning depends on what stands before them. After a list, the brackets hold a position number; after a dictionary, they hold a key. dict1['Price(kg)'] asks by name, not by position.
A dictionary is unordered — do not rely on the pairs having positions. There is no dict1[0]; the only way in is through a key. Asking with a key that does not exist in the dictionary is an error, so the key must be written exactly as it was stored, quotes and case included. …