Introduction to programming using Python

Session 7

Matthieu Choplin


  • To use tuples as immutable lists
  • To store key/value pairs in a dictionary and access value using the keys


  • Tuples are like lists except they are immutable. Once they are created, their contents cannot be changed.
  • If the contents of a list in your application do not change, you should use a tuple to prevent data from being modified accidentally. Furthermore, tuples are more efficient than lists.

Creating Tuples

  • With brackets `(` and `)`
  • t1 = () # Create an empty tuple
    t2 = (1, 3, 5)
  • By converting a list (comprehension here) into a tuple
  • t3 = tuple([2 * x for x in range(1, 5)])
  • By converting a string into a tuple
  • t4 = tuple("abac")

Tuples -- len(), max(), min(), [] index

  • Tuples can be used like lists except they are immutable
  • tuple2 = tuple([7, 1, 2, 23, 4, 5]) # Create a tuple from a list
    print("length is", len(tuple2)) # Use function len
    print("max is", max(tuple2)) # Use max
    print("min is", min(tuple2)) # Use min
    print("sum is", sum(tuple2)) # Use sum
    print("The first element is", tuple2[0]) # Use indexer

Tuples -- +, *, [:] slice, in

    tuple1 = ("green", "red", "blue") # Create a tuple
    tuple2 = tuple([7, 1, 2, 23, 4, 5]) # Create a tuple from a list
    tuple3 = tuple1 + tuple2 # Combine 2 tuples
    tuple3 = 2 * tuple1 # Multiply a tuple
    print(tuple2[2 : 4]) # Slicing operator
    print(2 in tuple2) # in operator
    for v in tuple1:
        print(v, end = " ")

Tuples -- +, *, [:] slice, in

    tuple1 = ("green", "red", "blue")
    tuple2 = tuple([7, 1, 2, 23, 4, 5])
    list1 = list(tuple2) # Obtain a list from a tuple
    tuple4 = tuple(list1)
    tuple5 = tuple(list1)
    print(tuple4 == tuple5) # Compare two tuples


  • Why dictionary?
  • Suppose your program stores a million students and frequently searches for a student using the social security number. An efficient data structure for this task is the dictionary. A dictionary is a collection that stores the elements along with the keys. The keys are like an indexer.

Key/value pairs

Creating a dictionary

Empty dictionary:

dictionary = {}
# or
dictionary = dict()

Populated dictionary:

dictionary = dict(john=40, peter=45)
# or
dictionary = {"john":40, "peter":45}
# or
dictionary = dict([('john',40), ('peter',45)])

Adding/Modifying Entries

To add an entry to a dictionary, use dictionary[key] = value

>>> dictionary["susan"] = 50
>>> print(dictionary)
{'john': 40, 'susan': 50, 'peter': 45}

Deleting Entries

To delete an entry from a dictionary, use del dictionary[key]

>>> del dictionary[“susan”]
>>> print(dictionary)
{'john': 40, 'peter': 45}

Looping Entries

for key in dictionary:
 print(key + ":" + str(dictionary[key]))

The len and in operators

len(dictionary) returns the number of the elements in the dictionary

>>> dictionary = {"john":40, "peter":45}
>>> "john" in dictionary
>>> "johnson" in dictionary
>>> len(dictionary)

The dictionary methods

Methods Meaning
list(dictionary.keys()): list Returns a dict_keys type of object, that you can convert in a sequence of values with list(dictionary.keys())
list(dictionary.values()): list Returns a dict_values type of object, that you can convert with list(dictionary.values())
list(dictionary.items()): tuple Returns a dict_items type of object, that you can convert in a sequence of tuples (key, value) with list(dictionary.items()).
clear(): None Deletes all entries.
get(key): value Returns the value for the key.
pop(key): value Removes the entry for the key and returns its value.

Exercise: dictionary manipulation

  1. Create a dictionary that you put in a variable 'birthdays' with the following data:
  2. 'Luke Skywalker': '5/24/19'
    'Obi-Wan Kenobi': '3/11/57'
    'Darth Vader':	'4/1/41'
  3. Write if statements that test to check if 'Yoda' and 'Darth Vader' exist as keys in the dictionary, then enter each of them with birthday value 'unknown' if their name does not exist as a key
  4. Display all the key-value pairs in the dictionary, one per line with a space between the name and the birthday, by looping over the dictionary's keys
  5. Delete 'Darth Vader' from the dictionary
  6. Bonus: Make the same dictionary by using dict() and passing in the initial values when you first create the dictionary

Exercise: Guess the capital

  • Write a program that prompts the user to enter a capital for a random country.
  • Upon receiving the user input, the program reports whether the answer is correct.
  • The countries and their capitals are stored in a dictionary in this file (import it to use).
  • The user’s answer is not case sensitive.


Hide solution

import random

from list_of_countries import COUNTRIES

def main():
    countries = list(COUNTRIES.keys())
    country_to_guess = random.choice(countries)
    capital = input("What is the capital of "
                    + country_to_guess + "? ").strip()

    if capital.lower() == COUNTRIES[country_to_guess]\
        print("Your answer is correct")
        print("The correct answer should be "
              + COUNTRIES[country_to_guess])