Skip to content

Computer Science · Ch 5 — Getting Started with Python

Mapping

5.7.5

Mapping

Mapping is an unordered data type in Python. Where a sequence looks items up by their integer position, a mapping looks values up by a key. Currently, Python has only one standard mapping data type: the dictionary.

(A) Dictionary

A dictionary holds data items as key-value pairs, with the whole collection enclosed in curly brackets { }. The essential syntax rules:

  • Every key is separated from its value by a colon : — each entry reads key : value.
  • Pairs are separated from one another by commas.
  • The keys are usually strings, while their values can be of any data type.

Dictionaries permit faster access to data: instead of scanning a collection for a match, the value is fetched directly through its key.

Accessing values by key

The key : value pairs of a dictionary are accessed using the key. To read any value, we specify its key in square brackets [ ] after the dictionary's name. The textbook's Example 5.8:

#create a dictionary
>>> dict1 = {'Fruit':'Apple', 'Climate':'Cold', 'Price(kg)':120}
>>> print(dict1)
{'Fruit': 'Apple', 'Climate': 'Cold', 'Price(kg)': 120}
>>> print(dict1['Price(kg)'])
120

Here three keys — 'Fruit', 'Climate' and 'Price(kg)' — map to the values 'Apple', 'Cold' and 120 respectively. Note the mix: two of the values are strings, one is an integer, which is perfectly legal since values may be of any type. The lookup dict1['Price(kg)'] returns 120 directly — no position numbers involved, just the key. …