0% found this document useful (0 votes)
30 views

Unit P8 - Complex Data Structures

This document provides an overview of sets and dictionaries as complex data structures in Python. It discusses how to build and use sets, including common set operations like union and intersection. It also covers creating and modifying sets by adding, removing, and clearing elements. The document intends to teach working with set and dictionary containers, as well as combining containers to model more complex data structures.

Uploaded by

ashenbandara007
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Unit P8 - Complex Data Structures

This document provides an overview of sets and dictionaries as complex data structures in Python. It discusses how to build and use sets, including common set operations like union and intersection. It also covers creating and modifying sets by adding, removing, and clearing elements. The document intends to teach working with set and dictionary containers, as well as combining containers to model more complex data structures.

Uploaded by

ashenbandara007
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 94

Unit P8:

Complex Data
Structures
SETS, DICTIONARIES, AND COMBINATIONS
OF DATA STRUCTURES
Chapter 8

This Photo by Unknown Author is licensed under CC BY-SA


Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 1
Unit Goals
▪ To build and use a set container
▪ To learn common set operations for processing data
▪ To build and use a dictionary container
▪ To work with a dictionary for table lookups

In this unit, we will learn how to work with two more types of
containers (sets and dictionaries) as well as how to combine
containers to model complex structures.

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 2


Contents
▪ Sets
▪ Dictionaries
▪ Complex Structures

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 3


Sets 8.1

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 4


Sets
▪ A set is a container that stores a collection of unique values
▪ Unlike a list, the elements or members of the set are not stored in
any particular order and cannot be accessed by position
▪ Operations are the same as the operations performed on sets in
mathematics
▪ Because sets do not need to maintain a particular order, set
operations are much faster than the equivalent list operations

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 5


Example Set
▪ This set contains three sets of colors––the colors of the British,
Canadian, and Italian flags
▪ In each set, the order does not matter, and the colors are not
duplicated in any one of the sets

uk_flag = { 'blue', 'red', 'white' }


ca_flag = { 'red', 'white' }
it_flag = { 'green', 'red', 'white' }

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 6


Creating and Using Sets
▪ To create a set with initial elements, you can specify the elements
enclosed in braces, just like in mathematics:
cast = { "Luigi", "Gumbys", "Spiny" }
The elements in a set are
inmutable and comparable

▪ Alternatively, you can use the set() function to convert any


sequence (a list, tuple, string, etc., etc.) into a set:
names = ["Luigi", "Gumbys", "Spiny"]
cast = set(names)

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 7


Creating an Empty Set
▪ For historical reasons, you cannot use {} to make an empty set in
Python (it refers to a dictionary)
▪ Instead, use the set() function with no arguments:
cast = set()

▪ As with any container, you can use the len() function to obtain
the number of elements in a set:

numberOfMovieCharacters = len(cast) # In this case it’s zero

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 8


Set Membership: in
▪ To determine whether an element is contained in the set, use the
in operator or its inverse, the not in operator:
if "Luigi" in cast :
print("Luigi is a character in Monty Python’s Flying Circus.")
else :
print("Luigi is not a character in the show.")

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 9


Accessing Set Elements
▪ Because sets are unordered, you cannot access the elements of a
set by position as you can with a list
▪ We use a for loop to iterate over the individual elements:
print("The cast of characters includes:")
for character in cast :
print(character)

▪ Note that the order in which the elements of the set are visited
depends on how they are stored internally – it’s unpredicable

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 10


Accessing Set Elements (2)
▪ For example, the previous loop above displays the following:
The cast of characters includes:
Gumbys
Spiny
Luigi
▪ Note that the order of the elements in the output is different from
the order in which the set was created

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 11


Displaying Sets In Sorted Order
▪ Use the sorted() function, which returns a list (not a set) of the
elements in sorted order
▪ The following loop prints the cast in sorted order:
for actor in sorted(cast) :
print(actor)

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 12


Adding Elements
▪ Sets are mutable collections, so you can add elements by using the
add() method:
cast = set(["Luigi", "Gumbys", "Spiny"]) #1
cast.add("Arthur") #2
cast.add("Spiny") #3

Arthur is not in the set, so it is added


to the set and the size of the set is
increased by one

Spiny is already in the set, so there is


no effect on the set

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 13


Removing Elements: discard()
▪ The discard() method removes an element if the element
exists:
cast.discard("Arthur") #4

▪ It has no effect if the given element is not a member of the set:


cast.discard("The Colonel") # Has no effect

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 14


Removing Elements: remove()
▪ The remove() method, on the other hand
o removes an element if it exists
o but raises an exception if the given element is not a member of the set:

cast.remove("The Colonel") # Raises an exception

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 15


Removing Elements: clear()
▪ The clear() method removes all elements of a set, leaving the
empty set:
cast.clear() # cast now has size 0

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 16


Subsets
▪ A set is a subset of another set if and only if every element of the
first set is also an element of the second set
▪ In the image below, the Canadian flag colors are a subset of the
British colors
▪ The Italian flag colors are not

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 17


The issubset() Method
▪ The issubset() method returns True or False to report
whether one set is a subset of another:
canadian = { "Red", "White" }
british = { "Red", "Blue", "White" }
italian = { "Red", "White", "Green" }

# True
if canadian.issubset(british) :
print("All Canadian flag colors appear in the British
flag.")

# True
if not italian.issubset(british) :
print("At least one of the colors in the Italian flag does
not.")

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 18


Set Equality / Inequality
▪ We test set equality with the “==” and “!=” operators
▪ Two sets are equal if and only if they have exactly the same
elements

french = { "Red", "White", "Blue" }


if british == french :
print("The British and French flags use the same colors.")

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 19


Set Union: union()
▪ The union of two sets contains all of the elements from both sets,
with duplicates removed
# inEither: The set {"Blue", "Green", "White", "Red"}
inEither = british.union(italian)

▪ Both British and Italian sets contain Red and White, but the union
is a set and therefore contains only one instance of each color

Note that the union() method returns


a new set. It does not modify either
of the sets in the call

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 20


Set Intersection: intersection()
▪ The intersection of two sets contains all of the elements that are in
both sets
# inBoth: The set {"White", "Red"}
inBoth = british.intersection(italian)

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 21


Difference of Two Sets: difference()
▪ The difference of two sets results in a new set that contains those
elements in the first set that are not in the second set

print("Colors that are in the Italian flag but not the


British:")
print(italian.difference(british)) # Prints {'Green'}

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 22


Common Set Operations

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 23


Common Set Operations (2)

Remember: union, intersection and difference return new sets


They do not modify the set they are applied to

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 24


Set operations using short operators

Set operation using methods Operators equivalence


x1.union(x2) x1 | x2
x1.intersection(x2) x1 & x2
x1.difference(x2) x1 - x2
x1.symmetric_difference(x2) x1 ^ x2
x1.issubset(x2) x1 <= x2
x1 < x2
x1.issuperset(x2) x1 >= x2
x1 > x2

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 25


Set Operations

https://www.programiz.com/python-programming/dictionary

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 26


Counting Unique Words

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 27


Problem Statement
▪ We want to be able to count the number of unique words in a text
document
o “Mary had a little lamb” has 57 unique words
▪ Our task is to write a program that reads in a text document and
determines the number of unique words in the document

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 28


Step One: Understand the Task
▪ To count the number of unique words in a text document we need
to be able to determine if a word has been encountered earlier in
the document
o Only the first occurrence of a word should be counted
▪ The easiest way to do this is to read each word from the file and
add it to the set
o Because a set cannot contain duplicates we can use the add method
o The add method will prevent a word that was encountered earlier from
being added to the set
▪ After we process every word in the document the size of the set
will be the number of unique words contained in the document

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 29


Step Two: Decompose the Problem
▪ Create an empty set
▪ for each word in the text document
o Add the word to the set
▪ Number of unique words = the size of the set
▪ Creating the empty set, adding an element to the set, and
determining the size of the set are standard set operations
▪ Reading the words in the file can be handled as a separate function

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 30


Step Three: Build the Set
▪ We need to read individual words from the file. For simplicity in
our example we will use a literal file name
inputFile = open(“nurseryrhyme.txt”, “r”)
For line in inputFile :
theWords = line.split()
For words in theWords :
Process word
▪ To count unique words we need to remove any nonletters and
remove capitalization
▪ We will design a function to “clean” the words before we add them
to the set

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 31


Step Four: Clean the Words
▪ To strip out all the characters that are not letters we will iterate
through the string, one character at a time, and build a new
“clean” word

def clean(string) :
result = ''
for char in string :
if char.isalpha() :
result = result + char
return result.lower()

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 32


Step Five: Put Everything Together
▪ Implement the main() function and combine it with the other
functions
▪ Open the file: countwords.py

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 33


Spell checking

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 34


Set Example: Spell Checking
▪ The program spellcheck.py reads a file that contains correctly
spelled words and places the words in a set
▪ It then reads all words from a document––here, the book Alice in
Wonderland––into a second set
▪ Finally, it prints all words from the document that are not in the set
of correctly spelled words
▪ Open the file spellcheck.py

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 35


Example: Spellcheck.py

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 36


Example: Spellcheck.py

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 37


Execution: Spellcheck.py

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 38


Programming Tip
▪ When you write a program that manages a collection of unique
items, sets are far more efficient than lists
▪ Some programmers prefer to use the familiar lists, replacing
itemSet.add(item)

▪ with:
if (item not in itemList)
itemList.append(item)

▪ However, the resulting program is much slower.


o The speed factor difference is over 10 times

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 39


Dictionaries 8.2

SECTION 8.2

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 40


Dictionaries
▪ A dictionary is a container that keeps associations between keys
and values
o Also called associative array or mapping
▪ Every key in the dictionary has an associated value
▪ Keys are unique, but a value may be associated with several keys
▪ Example (the mapping between key and value is indicated by an
arrow):

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 41


Dictionary syntax
{
"Romeo": "green",
"Adam": "purple",
"Eve": "blue",
"Juliet": "blue"
}

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 42


Syntax: Sets and Dictionaries

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 43


Creating Dictionaries
▪ Suppose you need to write a program that looks up the phone
number for a person in your mobile phone’s contact list
▪ You can use a dictionary where the names are keys and the phone
numbers are values

contacts = { "Fred": 7235591, "Mary": 3841212, "Bob":


3841212, "Sarah": 2213278 }

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 44


Duplicating Dictionaries: dict()
▪ You can create a duplicate copy of a dictionary using the dict()
function:
oldContacts = dict(contacts)

▪ You can create an empty dictionary

contacts = dict()
contacts = {}

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 45


Accessing Dictionary Values []
▪ The subscript operator [] is used to return the value associated
with a key
o Syntax: dictionary [ key ] # prints 7235591.
print("Fred's number is",
▪ The key may also be derived contacts["Fred"])
from a variable or an expression
▪ Note that the dictionary is not a sequence-type container like a list.
o You cannot access the items by index or position
o A value can only be accessed using its associated key

The key supplied to the subscript operator must be


a valid key in the dictionary or
a KeyError exception will be raised

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 46


Dictionaries: Checking Membership
▪ To find out whether a key is present in the dictionary, use the in
(or not in) operator:

if "John" in contacts :
print("John's number is", contacts["John"])
else :
print("John is not in my contact list.")

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 47


Missing Keys
▪ If you try to get a non-existent key, you get a KeyError
▪ You must check whether the key exists, before trying to retrieve
the value

if "Tony" in contacts:
print(contacts["Tony"])
else:
print("Missing")

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 48


Default Values
▪ As a shortcut, you may use the get method with a default value
o Syntax: dictionary.get(key, default)

▪ The default value is returned if there is no matching key

number = contacts.get("Tony", "missing")

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 49


Adding/Modifying Items
▪ A dictionary is a mutable container
▪ You can add a new item using the subscript operator [] (can’t be
done with a list!)
contacts["John"] = 4578102 #1

▪ To change the value associated with a given key, set a new value
using the [] operator on an existing key:
contacts["John"] = 2228102 #2

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 50


Adding New Elements Dynamically
▪ Sometimes you may not know which items will be contained in the
dictionary when it’s created
▪ You can create an empty dictionary :
favoriteColors = {}

▪ and add new items as needed:

favoriteColors["Juliet"] = "Blue"
favoriteColors["Adam"] = "Red"
favoriteColors["Eve"] = "Blue"
favoriteColors["Romeo"] = "Green"

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 51


Removing Elements
▪ To remove an item from a dictionary, call the pop() method with
the key as the argument:
contacts = { "Fred":
7235591, "Mary": 3841212,
"Bob": 3841212, "Sarah":
2213278 }

▪ This removes the entire item, both the key and its associated value

contacts.pop("Fred")

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 52


Removing and Storing Elements
▪ The pop() method returns the value of the item being removed,
so you can use it or store it in a variable:
fredsNumber = contacts.pop("Fred")

▪ Note: If the key is not in the dictionary, the pop method raises a
KeyError exception
o To prevent the exception from being raised, you should test for the key in
the dictionary:
if "Fred" in contacts :
contacts.pop("Fred")

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 53


Traversing a Dictionary
▪ You can iterate over the individual keys in a dictionary using a for
loop:
print("My Contacts:")
for key in contacts :
print(key)

▪ The result of this code fragment is :


My Contacts:
Sarah
Bob
John Note that the dictionary stores its
Mary items in an order that is optimized
for efficiency, which may not be the
Fred order in which they were added

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 54


Traversing a Dictionary: In Order
▪ To iterate through the keys in sorted order, you can use the
sorted() function as part of the for loop :
▪ Now, the contact list will be printed in order by name:
My Contacts:
Bob 3841212
print("My Contacts:")
Fred 7235591 for key in sorted(contacts) :
John 4578102 print("%-10s %d" % (key, contacts[key]))
Mary 3841212
Sarah 2213278

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 55


Iterating Dictionaries More Efficiently
▪ Python allows you to iterate over the items in a dictionary using
the items() method
▪ This is a bit more efficient than iterating over the keys and then
looking up the value of each key
▪ The items() method returns a sequence of tuples that contain
the keys and values of all items
o Here the loop variable item will be assigned a tuple that contains the key in
the first slot and the value in the second slot

for item in contacts.items() : for (key, val) in contacts.items() :


print(item[0], item[1]) print(key, val)

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 56


Example

for item in contacts.items() :


print(item[0], item[1])

for (key, val) in contacts.items() :


print(key, val)

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 57


Storing Data Records
▪ Data records, in which each record consists of multiple fields, are
very common
▪ In some instances, the individual fields of the record were stored in
a list to simplify the storage
person = [ 'John', 'Doe', 1971, 'New York', 'Student' ]
▪ But this requires remembering in which element of the list each
field is stored
o This can introduce run-time errors into your program if you use the wrong
list element when processing the record
o person[1] is the last name… or is it person[2]?
▪ In Python, it is common to use a dictionary to store a data record

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 58


Dictionaries: Data Records
▪ You create an item for each data record in which the key is the field
name and the value is the data value for that field
▪ For example, this dictionary named record stores a single student
record :
person = { “firstName”:‘John’, “lastName”:'Doe’,
“birthdate”: 1971, “city”: 'New York’, “profession”:
'Student’ }

▪ You may then create a list of such records


people = [ person1, person2, person3, ... ]

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 59


Dictionaries: Data Records
▪ To extract records from a file, we can define a function that reads a
single record and returns it as a dictionary
▪ E.g., if the file contains records made up of country names and
population data separated by a colon:

def extractRecord(infile) :
record = {}
line = infile.readline()
if line != "" :
fields = line.split(":")
record["country"] = fields[0]
record["population"] = int(fields[1])
return record

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 60


Dictionaries: Data Records
▪ The dictionary record that is returned has two items, one with the
key "country" and the other with the key "population"
▪ This function’s result can be used to print all of the records to the
terminal

infile = open("populations.txt", "r")


record = extractRecord(infile)
while len(record) > 0 :
print("%-20s %10d" % (record["country"],
record["population"]))
record = extractRecord(infile)

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 61


Common Dictionary Operations (1)

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 62


Common Dictionary Operations (2)

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 63


Dictionary Operations

https://www.programiz.com/python-programming/dictionary

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 64


Complex Data
Structures 8.3

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 65


Complex Structures
▪ Containers are very useful for storing collections of values
o In Python, the list and dictionary containers can contain any type of data,
including other containers
▪ Some data collections, however, may require more complex
structures
o In this section, we explore problems that require the use of a complex
structure

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 66


Example: A Dictionary of Sets
▪ The index of a book specifies on which pages each term occurs
▪ Build a book index from page numbers and terms contained in a
text file with the following format:
6:type
7:example
7:index
7:program
8:type
10:example
11:program
20:set

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 67


Example: A Dictionary of Sets
▪ The file includes every occurrence of every term to be included in
the index and the page on which the term occurs
▪ If a term occurs on the same page more than once, the index
includes the page number only once

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 68


Example: A Dictionary of Sets
▪ The output of the program should be a list of terms in alphabetical
order followed by the page numbers on which the term occurs,
separated by commas, like this:
example: 7, 10
index: 7
program: 7, 11
type: 6, 8
set: 20

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 69


Example: A Dictionary of Sets
▪ A dictionary of sets would be appropriate for this problem
▪ Each key can be a term and its corresponding value a set of the
page numbers where it occurs

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 70


Why Use a Dictionary?
▪ The terms in the index must be unique
o By making each term a dictionary key, there will be only one instance of
each term.
▪ The index listing must be provided in alphabetical order by term
o We can iterate over the keys of the dictionary in sorted order to produce the
listing
▪ Duplicate page numbers for a term should only be included once
o By adding each page number to a set, we ensure that no duplicates will be
added
o We don’t need a dictionary because there is no extra information associated
to page numbers

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 71


Dictionary Sets: Buildindex.py

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 72


Dictionary Sets: Buildindex.py

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 73


Dictionary Sets: Buildindex.py

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 74


Dictionary Sets: Buildindex.py

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 75


Example: A Dictionary of Lists
▪ A common use of dictionaries in Python is to store a collection of
lists in which each list is associated with a unique name or key
▪ For example, consider the problem of extracting data from a text
file that represents the yearly sales of different ice cream flavors in
multiple stores of a retail ice cream company
vanilla:8580.0:7201.25:8900.0
chocolate:10225.25:9025.0:9505.0
rocky road:6700.1:5012.45:6011.0
strawberry:9285.15:8276.1:8705.0
cookie dough:7901.25:4267.0:7056.5

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 76


Example: A Dictionary of Lists
▪ The data is to be processed to produce a report similar to the
following:

▪ A simple list is not the best choice:


o The entries consist of strings and floating-point values, and they have to be
sorted by the flavor name

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 77


Example: A Dictionary of Lists
▪ With this structure, each row of the table is an item in the
dictionary
▪ The name of the ice cream flavor is the key used to identify a
particular row in the table.
▪ The value for each key is a list that contains the sales, store by
store, for that flavor of ice cream

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 78


Example: Icecreamsales.py

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 79


Example: Icecreamsales.py

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 80


Example: Icecreamsales.py

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 81


Example: Icecreamsales.py

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 82


Example: Icecreamsales.py

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 83


Modules 8.3

SPLIT TING OUR PROGRAMS INTO PIECES

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 84


Modules
▪ When you write small programs, you can place all your code into a
single source file
▪ When your programs get larger or you work in a team, that
situation changes
▪ You will want to structure your code by splitting it into separate
source files (a “module”)

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 85


Reasons for Employing Modules
▪ Large programs can consist of hundreds of functions that become
difficult to manage and debug if they are all in one source file
o By distributing the functions over several source files and grouping related
functions together, it becomes easier to test and debug the various
functions
▪ The second reason becomes apparent when you work with other
programmers in a team
o It would be very difficult for multiple programmers to edit a single source
file simultaneously
o The program code is broken up so that each programmer is solely
responsible for a unique set of files

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 86


Typical Division Into Modules
▪ Large Python programs typically consist of a driver module and one
or more supplemental modules
▪ The driver module contains the main() function or the first
executable statement if no main function is used
▪ The supplemental modules contain supporting functions,
constants, variables, …

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 87


Modules Example
▪ Goal: Splitting the dictionary of lists into modules
▪ The tabulardata.py module contains functions for reading the
data from a file and printing a dictionary of lists with row and
column totals
▪ The salesreport.py module is the driver (or main) module that
contains the main function
▪ By splitting the program into two modules, the functions in the
tabulardata.py module can be reused in another program that
needs to process named lists of numbers

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 88


Using Code That are in Modules
▪ To call a function or use a constant variable that is defined in a user
module, you can first import the module in the same way that you
imported a standard library module:
from tabulardata import readData, printReport

▪ However, if a module defines many functions, it is easier to use the


form:
import tabulardata

▪ With this form, you must prepend the name of the module to the
function name:
tabulardata.printReport(salesData)

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 89


Summary

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 90


Python Sets
▪ A set stores a collection of unique values
▪ A set is created using a set literal {…} or the set() function
▪ The in operator is used to test whether an element is a member of
a set
▪ New elements can be added using the add() method
▪ Use the discard() method to remove elements from a set
▪ The issubset() method tests whether one set is a subset of
another set

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES Page 91


Python Sets
▪ The union() method produces a new set that contains the
elements in both sets
▪ The intersection() method produces a new set with the
elements that are contained in both sets
▪ The difference() method produces a new set with the
elements that belong to the first set but not the second
▪ The implementation of sets arrange the elements in the set so that
they can be located quickly

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES Page 92


Python Dictionaries
▪ A dictionary keeps associations between keys and values
▪ Use the [] operator to access the value associated with a key
o Use the get() method to define a default value if the key isn’t found
▪ The in operator is used to test whether a key is in a dictionary
▪ New entries can be added, or existing entries can be modified
using the [] operator
▪ Use the pop() method to remove a dictionary entry

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES Page 93


Complex Structures
▪ Complex structures can help to better organize data for processing
▪ The code of complex programs is distributed over multiple files

Politecnico di Torino, 2021/22 INFOMATICA / COMPUTER SCIENCES 94

You might also like