This lesson is being piloted (Beta version)

Dictionaries

Overview

Teaching: 15 min
Exercises: 15 min
Questions
  • What is a dictionary?

Objectives
  • Create dictionaries.

  • Add and retrieve values from a dictionary, and test for membership.

  • Iterate over a dictionary.

What is a dictionary?

A dictionary is a data structure similar to a list, but that uses keys instead of indexes. It is the Python implementation of an associative container, or key-value store.

Each value in the dictionary is looked up using a key and new entries can be added by assigning to a non-existent key.

Creating dictionaries

Dictionaries are created with {}, instead of [] for lists, or () for tuples.

For example, a phonebook can be created with:

phonebook = {}
phonebook["Carolina"] = 55512341
phonebook["Rhys"] = 55512342
phonebook["Christian"] = 55512343
phonebook
{'Carolina': 55512341, 'Rhys': 55512342, 'Christian': 55512343}

Alternatively, the following (key : value) shorthand can be used to initialise a dictionary:

phonebook = {
    "Carolina" : 55512341,
    "Rhys" : 55512342,
    "Christian" : 55512343
}
phonebook
{'Carolina': 55512341, 'Rhys': 55512342, 'Christian': 55512343}

A key can be a string, a number, or any hashable object (which roughly means no lists or other mutable containers).

You can even mix key types in a single dictionary although it tends to be confusing (you often wish to sort on the keys later!):

phrasebook = {
    1 : "Is 1 a page number?",
    "My tank is full of smolts" : "Vamos a la playa!",
    2 : "Does 2 come before or after 'my tank'?",
    (2, '9-12') : "sacred relic"
}
phrasebook
{1: 'Is 1 a page number?',
 'My tank is full of smolts': 'Vamos a la playa!',
 2: "Does 2 come before or after 'my tank'?",
 (2, '9-12'): 'sacred relic'}

Adding and modifying values in a dictionary

You can assign to an individual dictionary entry to add it or modify it using the following syntax: mydict[key] = "value"

Adding and changing entries in the phonebook

Add your phone number to the following phonebook, and then change the entry for “Christian”.

phonebook = {
   "Carolina" : 55512341,
   "Rhys" : 55512342,
   "Christian" : 55512343
}

Solution

phonebook['My_number'] = 55567676
phonebook['Christian'] = 55534343
phonebook
{'Carolina': 55512341,
'Rhys': 55512342,
'Christian': 55534343,
'My_number': 55567676}

We can check the length of our updated dictionary using the function len.

Retrieving and removing values from a dictionary

Lets create an English-Aboriginal(Ngunnawal) dictionary.

Abor_dict = {
    "Bird" : "Bimbi",
    "Flowers" : "Gamburra",
    "Moon" : "Kubbadang",
    "Canoe" : "Mundang"
}
Abor_dict
{'Bird' : 'Bimbi', 'Flowers' : 'Gamburra', 'Moon' : 'Kubbadang', 'Canoe' : 'Mundang'}

To retrieve a value from a dictionary we use square [] brackets with the specific key

print(Abor_dict['Bird'])
print(Abor_dict['Canoe'])
Bimbi
Mundang

To remove a specific element from a dictionary, you can use the statement del and index the element using its key.

Remove a word from this dictionary

Remove the word ‘Bird’ from the English-Aboriginal(Ngunnawal) dictionary.

Abor_dict = {
   "Bird" : "Bimbi",
   "Flowers" : "Gamburra",
   "Moon" : "Kubbadang",
   "Canoe" : "Mundang"}

Solution

del Abor_dict['Bird']

Alternatively, if we want to return the value of the entry being removed we can use the method .pop, you can try this by typing mydict.pop("Dog").

Testing membership (is my item in the dictionary or not?)

Check if a key exists in a given dictionary by using the in operator like this:

motifs = {
    "m1" : "AGTTGC",
    "m2" : "TTTGCG",
    "m3" : "GTGTAA",
    "m4" : "AAATGC"}

print('m1' in motifs)
print('m3' in motifs)
print('m5' in motifs)
True
True
False

Iterating over a dictionary

We can iterate over a dictionary using a for loop to get both keys and keys:values. Going back to our motifs dictionary, iterate over the dictionary to get all the keys.

for key in motifs:
    print(key)
m1
m2
m3
m4

How to iterate over a dictionary to get all key,value pairs

Construct a for loop to extract both keys and values from the motifs dictionary. Hint: you will need to use a dictionary method

motifs = {
   "m1" : "AGTTGC",
   "m2" : "TTTGCG",
   "m3" : "GTGTAA",
   "m4" : "AAATGC"}

Solution

for item in motifs.items():
    print(items)
('m1', 'AGTTGC')
('m2', 'TTTGCG')
('m3', 'GTGTAA')
('m4', 'AAATGC')

Alternatively, if we want to return the keys and values as separate items we can use:

for key, value in motifs.items():
    print(key, ":", value)
m1 : AGTTGC
m2 : TTTGCG
m3 : GTGTAA
m4 : AAATGC

Note: As of Python 3.7, iterating over items in a dictionary is now done in the order in which they were inserted as a “feature” of the language.

Sets

What is a set?

How to create a set?

# set of integers
my_set = {1, 2, 3}
print(my_set)

# set of mixed datatypes
my_set = {1.0, "Hello", (1, 2, 3)}
print(my_set)

# set do not have duplicates
my_set = {1, 2, 3, 4, 3, 2}
print(my_set)
{1, 2, 3}
{1.0, 'Hello', (1, 2, 3)}
{1, 2, 3, 4}
# here [3, 4] is a mutable list
# the following command will cause an error:
# my_set = {1, 2, [3, 4]}
TypeError: unhashable type: 'list'

How to change a set in Python?

# create a set
my_set = {1,3}
print(my_set)

# add an element
my_set.add(2)
print(my_set)

# add multiple elements
my_set.update([2,3,4])
print(my_set)

# add list and set
my_set.update([4,5,1,1], {1,6,7,8}) 
print(my_set)
{1, 3}
{1, 2, 3}
{1, 2, 3, 4}
{1, 2, 3, 4, 5, 6, 7, 8}

Python set operations

Sets can be used to carry out mathematical set operations like union, intersection, difference and symmetric difference. We can do this with operators or methods:

Python set operation exercises

Solve the following operations:

print(A - B)
print(B - A)
print(A.intersection(B))
print(A ^ B)
print(A.union(B) & B.intersection(A))
print(B.intersection(A) - A.union(B))

Solution

{1, 2, 3, 4, 11}
{7, 8, 9, 10, 15}
{13, 5, 6, 14}
{1, 2, 3, 4, 7, 8, 9, 10, 11, 15}
{5, 13, 6, 14}
set()

Note that set() represents an empty set.

Key Points

  • A dictionary is a data structure similar to a list, but that uses keys instead of indexes.

  • Dictionaries are created with {}, instead of [] for lists, or () for tuples.

  • A dictionary key can be a string, a number, or any hashable object.

  • To retrieve a value for a specific key we use the method .get.

  • Check if a key exists in a given dictionary by using the in operator.

  • We can iterate over a dictionary using a for loop to get both keys and keys:values.

  • A set is an unordered collection of items. Every element is unique and immutable.

  • Sets can be used to perform mathematical set operations like union, intersection, symmetric difference.