GET214: COMPUTING AND SOFTWARE ENGINEERING
(Programming in Python)
LESSON 6: PYTHON DATA STRUCTURES II – TUPLES & DICTIONARIES
Learning Outcomes:
At the end of the lesson, students should be able to:
1. Describe the features and benefits of a tuple
2. Develop a program that creates and uses a tuple successfully
3. Identify and discuss the mutability of a tuple
4. Describe the structure of python dictionaries
5. Create a dictionary object with given key/value pairs
6. Demonstrate ability to access, evaluate and modify dictionary objects
7. Recognize and implement mutability of dictionary objects
8. Iterate through dictionary items
9. Use dictionary comprehension to create dictionary objects
6.1 What is a tuples?
A tuple is a sequence of comma separated values that can contain elements of
different types. A tuple must be created with commas between values, and
conventionally the sequence is surrounded by parentheses. It is used to store multiple
values in one variable. Items stored in a tuple are ordered and unchangeable
(immutable). A tuple is a type of sequence that resembles a list, except that, unlike a
list, a tuple is immutable. You indicate a tuple literal in Python by enclosing its
elements in parentheses instead of square brackets.
Tuples are usually diploid in scenarios where the data needs to be protected against
modification since tuples are immutable. It should be noted that lists can be
converted to tuples using the tuple() function.
6.2 Tuple creation and initialization
The following codes creates variable of tuple types:
T1 = (2, 5, 1, 6)
T2 = ()
T3 = (7,)
Food = ('fish', 'poultry', 'apple', 'banana')
1
6.3 Declaring a singleton tuple
In the previous initialization, T3 = (7,) is a tuple of one element, also known
generally as a singleton. This is the only case where the last element of tuple has a
trailing comma (,). Having a tuple a declaration like T = (7) will make T an integer
rather than a tuple. The following code and the accompanying output illustrate this.
6.4 Tuples Operation
Like lists, tuples supports a number of operations. We can access individual elements
of a tuple with the index [] operator. Negative indexes and slice operators also work
on tuples as they do in lists and strings. The len() function returns the number of
elements of in a tuple. The following example illustrate the common operations with
tuples.
2
6.5 Iterating through a Tuple
Like lists and strings, a for loop can be used to iterate through individual elements
of a tuple as shown below.
6.6 Sorting a Tuple
The sorted() function is used to sort elements of a tuple as shown below.
6.7 Python Dictionary
A dictionary in Python is a container object including key-value pairs. An example
of a key-value item is a word in an English dictionary with its corresponding
definition. The dict type implements a dictionary in Python. Since a dictionary
object is used to look up values using keys, a dictionary object cannot hold duplicate
key values.
6.8 Creating a dictionary
Two methods exist for creating an empty dictionary:
Using curly braces {}. Example: dict_1 = {}.
Using the dict() function. Example: dict_2 = dict().
3
A dictionary object can also be created with initial key-value pairs enclosed in
curly braces.
my_dict = {"pizza": 2, "pasta": 3, "drink": 4}
The above creates a dictionary object my_dict. A key and associated value are
separated by a colon, and key-value pairs are separated by commas.
6.9 dict() for dictionary creation
A dictionary object can be created with initial key-value pairs using the dict()
function.
Creating a dictionary from a list of tuples.
my_list = [("apple", 2), ("banana", 3), ("orange", 4)]
my_dict = dict(my_list)
Creating a dictionary using keyword arguments.
my_dict = dict(apple=2, banana=3, orange=4)
Creating a dictionary from another dictionary.
old_dict = {"apple": 2, "banana": 3, "orange": 4}
new_dict = dict(old_dict)
Activity 6.1 Personal information dictionary
Create a dictionary, my_info, with three key-value pairs. The keys should be "first
name", "last name", and "age" with the values being corresponding information
about yourself. Then, print my_info.
6.10 Accessing Dictionary Items
In Python, values associated with keys in a dictionary can be accessed using the
keys as indexes. Here are two ways to access dictionary items in Python:
Square bracket notation: Square brackets [] with the key inside access the
value associated with that key. If the key is not found, an exception will be
thrown.
4
get() method: The get() method is called with the key as an argument to
access the value associated with that key. If the key is not found, the method
returns None by default, or a default value specified as the second argument.
Example:
In the code below, a dictionary object my_dict is initialized with items {"apple": 2,
"banana": 3, "orange": 4}. The square bracket notation and get() method are used to
access values associated with the keys "banana" and "apple", respectively. When
accessing the dictionary to obtain the key "pineapple", -1 is returned since the key
does not exist in the dictionary.
my_dict = {"apple": 2, "banana": 3, "orange": 4}
print(my_dict["banana"]) # Prints: 3
print(my_dict.get("apple")) # Prints: 2
print(my_dict.get("pineapple", -1)) # Prints: -1
6.11 Obtaining dictionary keys and values
Dictionary keys, values, and both keys and values can be obtained using keys(),
values(), and items() function calls, respectively. The return type of keys(), values(),
and items() are dict_keys, dict_values, and dict_items, which can be converted to a
list object using the list constructor list().
5
6.12 Dictionary Mutability
In Python, a dictionary is a mutable data type, which means that a dictionary's
content can be modified after creation. Dictionary items can be added, updated, or
deleted from a dictionary after a dictionary object is created.
To add an item to a dictionary, either the square bracket notation or update() function
can be used.
Square bracket notation: When using square brackets to create a new key
object and assign a value to the key, the new key-value pair will be added to
the dictionary.
my_dict = {"apple": 2, "banana": 3, "orange": 4}
my_dict["pineapple"] = 1
print(my_dict)
# Prints: {"apple": 2, "banana": 3, "orange": 4,
#"pineapple": 1}
update() method: the update() method can be called with additional key-
value pairs to update the dictionary content.
my_dict = {"apple": 2, "banana": 3, "orange": 4}
my_dict.update({"pineapple": 1, "cherry": 0})
print(my_dict)
# Prints: {"apple": 2, "banana": 3, "orange": 4,
#"pineapple": 1, "cherry": 0}
To modify a dictionary item, the two approaches above can be used on an existing
dictionary key along with the updated value.
Square bracket notation:
my_dict = {"apple": 2, "banana": 3, "orange": 4}
my_dict["apple"] = 1
print(my_dict)
# Prints: {"apple": 1, "banana": 3, "orange": 4}
6
update() method:
my_dict = {"apple": 2, "banana": 3, "orange": 4}
my_dict.update({"apple": 1})
print(my_dict)
# Prints: {"apple": 1, "banana": 3, "orange": 4}
Items can be deleted from a dictionary using the del keyword or the pop() method.
• del keyword:
my_dict = {"apple": 2, "banana": 3, "orange": 4}
del my_dict["orange"]
print(my_dict) # Prints: {"apple": 2, "banana": 3}
• pop() method:
my_dict = {"apple": 2, "banana": 3, "orange": 4}
deleted_value = my_dict.pop("banana")
print(deleted_value) # Prints: 3
print(my_dict) # Output: {"apple": 2, "orange": 4}}
Activity 6.2: The number of unique characters
Given a string value, calculate and print the number of unique characters using a
dictionary.
Input:
string_value = "This is a string"
Output: 10
Activity 6.3: Character count in a string
Given a string value, calculate and print the number of occurrences of all characters
using a dictionary.
Input:
string_value = "This is a string"
Output:
{"T": 1, "h": 1, "i": 3, "s": 3, " ": 3, "a": 1, "t": 1, "r": 1, "n": 1, "g": 1}
7
6.13 Looping through a dictionary
Looping over a Python dictionary is a way to iterate through key-value pairs in the
dictionary. Looping in a dictionary can be done by iterating over keys or items.
When looping using keys, keys are obtained using the keys() function and are passed
to the loop variable one at a time. When looping over items using the items() function,
both the key and value for each item are passed to the loop variable.
The following example illustrates the concept of looping through a dictionary.
6.14: Dictionary Comprehension
Dictionary comprehension is a concise and efficient way to create a dictionary in
Python. With dictionary comprehension, elements of an iterable object are
transformed into key-value pairs. The syntax of dictionary comprehension is similar
to list comprehension, but instead of using square brackets, curly braces are used to
define a dictionary.
Here is a general syntax for dictionary comprehension:
{key_expression: value_expression for element in iterable}
Example