6. Dictionaries#
Like a list, a dictionary is a data structure which can be used to store multiple items. In the case of a dictionary, each item consists of two parts: a key and a value. These keys need to be specified explicitly when you add an item to a dictionary. They can be of any type.
Creating a dictionary#
There are multiple ways to create a dictionary.
One way is to use the dict()
function. This function results in an empty dictionary.
language_code = dict()
We can add items to this dictionary one by one. To do this, we firstly need to mention the key in a set of square brackets, directly following the name of the dictionary. The value to be associated with this key needs to be given to the right of the assignment operator. Importantly, each of these keys needs to be unique. In the example below, the keys and the values are all strings.
language_code['dut'] = 'Dutch'
language_code['fre'] = 'French'
language_code['eng'] = 'English'
language_code['ger'] = 'German'
language_code['spa'] = 'Spanish; Castilian'
We saw that, in the case of lists, we can look up values in a list by their index, which is always a number. The items in a dictionary can be accessed in a similar way. We can access the individual items of the dictionary by mentioning the keys of these items inside square brackets. The code below prints the values that are associated with the two keys that are provided.
print( language_code['dut'] )
## This prints 'Dutch'
print( language_code['ger'] )
## This prints 'German'
Just like regular variables, you can overwrite values in dictionaries by assigning a different value to the key.
language_code['spa'] = 'Spanish'
Exercise 6.1.#
The keys in a dictionary may consist of labels describing the values we are dealing with. The dictionary named person_data
in the cell below is used to capture biographical information. Use this dictionary to print the following sentence:
“Isaac Newton was born in 1642 in Woolsthorpe.”
person_data = dict()
person_data['first_name'] = 'isaac'
person_data['last_name'] = 'newton'
person_data['year_of_birth'] = 1642
person_data['place_of_birth'] = 'woolsthorpe'
Non-existing keys#
As was mentioned, the individual items of the dictionaries can be accessed using their keys. When you reference a key that does not actually exist in the dictionary, however, the code produces an error (more specifically: a KeyError
). It is evidently impossible to retrieve a value for a key that does not exist.
print(language_code['ita'])
To avoid such error messages, you can make use of the get()
method. As the first parameter, you need to mention the key of the item that you want to retrieve. If the key does indeed exist, the get()
method returns the value associated with this key. If it does not exist, the methods returns None
.
print( language_code.get( 'eng' ) )
print( language_code.get( 'ita' ) )
# prints None
It is also possible to provide a default value which should be returned when the key that was supplied does not exist, as a second paramater of get()
.
Because the key ‘ita’ has not been set yet in the dictionary named ‘language_code’, the code below prints the string ‘[Undefined]’, which is the value that is supplied as a second parameter.
print( language_code.get( 'ita', '[Undefined]' ) )
A second way of creating dictionaries#
Instead of starting with an empty dictionary, and adding items one by one, it is also possible to populate full dictionaries upon their creation using a syntax that makes use of curly brackets. Within these brackets, you need to list all the needed key and value pairs.
The keys and the values need to be separated by a colon. All individual items in the dictionary (i.e. the full key and value pairs) need to separated by commas. The keys and the values may be provided on separate lines.
country_code = { 'ec':'Ecuador',
'af':'Afghanistan',
'dk':'Denmark',
'tr':'Turkey',
'ao':'Angola' ,
'be':'Belgium',
'ma':'Marocco',
'br':'Brazil',
'cn':'China' }
Exercise 6.2.#
Create a dictionary that can be used to connect ISBN codes to the titles of the books they identify. The name of this dictionary must be books_by_isbn
. Using the second method that was discussed to create a dictionaries.
Upon its creation, the dictionary should be assigned the following items:
ISBN: 9780143105985
title: 'White Noise'
ISBN: 9781447289395
Title: 'Underworld'
After this, write code to add the following book individually:
ISBN: 9780330452236
Title: 'Falling Man'
Finally, print a list of all the novels in the dictionary ‘books_by_isbn’. For each item in the dictionary, print the sentence ‘The ISBN of the novel ‘[title]’ is [ISBN]’.
Exercise 6.3.#
The cell below creates a dictionary named language_code
and a list named language_code
. Using these two variables, try to print the names of the languages that are given in the list named languages
. The output should look as follows:
The list contains the following countries:
German
Spanish
English
language_code = dict()
language_code['dut'] = 'Dutch'
language_code['fre'] = 'French'
language_code['eng'] = 'English'
language_code['ger'] = 'German'
language_code['spa'] = 'Spanish'
language_code['por'] = 'Portuguese'
language_code['swe'] = 'Swedish'
languages = ['ger','spa','eng']
Sorting a dictionary#
By default, all the items in this dictionary are shown in the order in which they were added to the dictionary.
A dictionary can be sorted by its keys using the in-built sorted()
function. Strings are sorted alphabetically and integers and floats are sorted numerically.
Strings are sorted alphabetically and integers and floats are sorted numerically.
for code in sorted(country_code):
print(f'"{code}" is the code for "{country_code[code]}"')
"af" is the code for "Afghanistan"
"ao" is the code for "Angola"
"be" is the code for "Belgium"
"br" is the code for "Brazil"
"cn" is the code for "China"
"dk" is the code for "Denmark"
"ec" is the code for "Ecuador"
"ma" is the code for "Marocco"
"tr" is the code for "Turkey"
It is also possible to sort a dictionary by its values, but that is outside the scope of this tutorial.
Exercise 6.4.#
The dictionary named country_continent
, defined below, connects the names of countries to the continents they are on.
Print a list of all the countries in this dictionary that are in Asia. The list needs to be sorted alphabetically.
country_continent = {
"Belgium":"Europe",
"France":"Europe",
"Italy":"Europe",
"China":"Asia",
"Thailand":"Asia",
"Japan":"Asia",
"India":"Asia",
"Bangladesh":"Asia",
"Ghana":"Africa",
"Tunesia":"Africa" }
Exercise 6.5.#
The dictionary named eu_capitals
connects the countries in the European Union to their capitals.
# Create the dictionary
eu_capitals = {
'Italy': 'Rome', 'Luxembourg': 'Luxembourg',
'Belgium': 'Brussels', 'Denmark': 'Copenhagen',
'Finland': 'Helsinki', 'France': 'Paris',
'Slovakia': 'Bratislava', 'Slovenia': 'Ljubljana',
'Germany': 'Berlin', 'Greece': 'Athens',
'Ireland': 'Dublin', 'Netherlands': 'Amsterdam',
'Portugal': 'Lisbon', 'Spain': 'Madrid',
'Sweden': 'Stockholm',
'Cyprus': 'Nicosia', 'Lithuania': 'Vilnius',
'Czech Republic': 'Prague', 'Estonia': 'Tallin',
'Hungary': 'Budapest', 'Latvia': 'Riga',
'Malta': 'Valetta', 'Austria': 'Vienna',
'Poland': 'Warsaw', 'Croatia': 'Zagreb',
'Romania': 'Bucharest', 'Bulgaria': 'Sofia'
}
Using this dictionary, print a sentence which gives information about the current number of countries in the EU. The number of items in a dictionary can be determined using the len()
function.
# How many countries are in the EU dictionary?
For each country, print the following sentence: “The capital of [ country ] is [ capital ].”
# Print the capitals of these countries