Creating Dictionaries

A dictionary associates keys with values. Each key maps to a specific value. The following table contains examples of dictionaries with their keys, key types, values and value types:

A dictionary’s keys must be unique (that is, no duplicates). Multiple keys can have the same value, such as two different inventory codes that have the same quantity in stock.

You can create a dictionary by enclosing in curly braces, {}, a comma-separated list of key– value pairs, each of the form key: value. You can create an empty dictionary with {}. Let’s create a dictionary with the country-name keys ‘Finland’, ‘South Africa’ and ‘Nepal’ and their corresponding Internet country code values ‘fi’, ‘za’ and ‘np’:

country_codes = {‘Finland’: ‘fi’, ‘South Africa’: ‘za’, ‘Nepal’: ‘np’}
print(country_codes)

When you output a dictionary, its comma-separated list of key–value pairs is always enclosed in curly braces. Because dictionaries are unordered collections, the display order can differ from the order in which the key–value pairs were added to the dictionary. In the code segment above, the key–value pairs are displayed in the order they were inserted, but do not write code that depends on the order of the key–value pairs.

Empty Dictionary?

The built-in function `len` returns the number of key–value pairs in a dictionary:
country_codes = {‘Finland’: ‘fi’, ‘South Africa’: ‘za’, ‘Nepal’: ‘np’}
print(len(country_codes)) # Displays 3

Iterating through a Dictionary

The following dictionary maps month-name strings to int values representing the numbers of days in the corresponding month. Note that multiple keys can have the same value:

days_per_month = {‘January’: 31, ‘February’: 28, ‘March’: 31}

Again, the dictionary’s string representation shows the key–value pairs in their insertion order, but this is not guaranteed because dictionaries are unordered. We’ll show how to process keys in sorted order later in this chapter. The following for statement iterates through days_per_month key–value pairs.

for month, days in days_per_month.items():
	print(month, “ has ”, days, “ days”)