Unit P8 - Complex Data Structures
Unit P8 - Complex Data Structures
Complex Data
Structures
SETS, DICTIONARIES, AND COMBINATIONS
OF DATA STRUCTURES
Chapter 8
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.
▪ As with any container, you can use the len() function to obtain
the number of elements in a set:
▪ Note that the order in which the elements of the set are visited
depends on how they are stored internally – it’s unpredicable
# 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.")
▪ Both British and Italian sets contain Red and White, but the union
is a set and therefore contains only one instance of each color
https://www.programiz.com/python-programming/dictionary
def clean(string) :
result = ''
for char in string :
if char.isalpha() :
result = result + char
return result.lower()
▪ with:
if (item not in itemList)
itemList.append(item)
SECTION 8.2
contacts = dict()
contacts = {}
if "John" in contacts :
print("John's number is", contacts["John"])
else :
print("John is not in my contact list.")
if "Tony" in contacts:
print(contacts["Tony"])
else:
print("Missing")
▪ To change the value associated with a given key, set a new value
using the [] operator on an existing key:
contacts["John"] = 2228102 #2
favoriteColors["Juliet"] = "Blue"
favoriteColors["Adam"] = "Red"
favoriteColors["Eve"] = "Blue"
favoriteColors["Romeo"] = "Green"
▪ This removes the entire item, both the key and its associated value
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")
def extractRecord(infile) :
record = {}
line = infile.readline()
if line != "" :
fields = line.split(":")
record["country"] = fields[0]
record["population"] = int(fields[1])
return record
https://www.programiz.com/python-programming/dictionary
▪ With this form, you must prepend the name of the module to the
function name:
tabulardata.printReport(salesData)