Introduction to Computing Using Python Dictionary container class




















- Slides: 20

Introduction to Computing Using Python Dictionary container class + modules § Container Class dict § Modules, revisited

Introduction to Computing Using Python User-defined indexes and dictionaries Goal: a container of employee records indexed by employee SS# Problems: • the range of SS#s is huge • SS#s are not really integers >>> employee[987654321] ['Yu', 'Tsun'] >>> employee[864209753] ['Anna', 'Karenina'] >>> employee[100010010] ['Hans', 'Castorp'] Solution: the dictionary class dict key value '864 -20 -9753' ['Anna', 'Karenina'] '987 -65 -4321' ['Yu', 'Tsun'] '100 -01 -0010' ['Hans', 'Castorp'] A dictionary contains (key, value) pairs >>> employee = { '864 -20 -9753': ['Anna', 'Karenina'], '987 -65 -4321': ['Yu', 'Tsun'], '100 -01 -0010': ['Hans', 'Castorp']} >>> employee['987 -65 -4321'] ['Yu', 'Tsun'] >>> employee['864 -20 -9753'] ['Anna', 'Karenina'] A key can be used as an index to access the corresponding value

Introduction to Computing Using Python Properties of dictionaries Dictionaries are not ordered Dictionaries are mutable • new (key, value) pairs can be added • the value corresponding to a key can be modified The empty dictionary is {} Dictionary keys must be immutable >>> employee = { '864 -20 -9753': ['Anna', 'Karenina'], >>> employee ={ '987 -65 -4321': ['Yu', 'Tsun'], '864 -20 -9753': ['Anna', 'Karenina'], >>> employee ={ '100 -01 -0010': ['Anna', ['Hans', 'Castorp']} '987 -65 -4321': ['Yu', 'Tsun'], '864 -20 -9753': 'Karenina'], >>> employee '100 -01 -0010': ['Yu', ['Hans', 'Castorp']} '987 -65 -4321': 'Tsun'], {'100 -01 -0010': ['Hans', 'Castorp'], ['Anna', >>> employee '100 -01 -0010': ['Hans', '864 -20 -9753': 'Castorp']} 'Karenina'], '987 -65 -4321': ['Yu', 'Tsun']} {'100 -01 -0010': ['Hans', 'Castorp'], '864 -20 -9753': ['Anna', >>> employee >>> 'Karenina'], '987 -65 -4321': ['Yu', 'Tsun']} {'100 -01 -0010': ['Hans', 'Castorp'], '864 -20 -9753': ['Anna', >>> employee['123 -45 -6789'] = 'Holden 'Karenina'], '987 -65 -4321': ['Yu', 'Tsun']} Cafield' employee >>> employee['123 -45 -6789'] = 'Holden Cafield' {'100 -01 -0010': >>> employee ['Hans', 'Castorp'], '864 -20 -9753': ['Anna', 'Karenina'], '987 -65 -4321': ['Yu', 'Tsun'], '123 -45 -6789': {'100 -01 -0010': ['Hans', 'Castorp'], '864 -20 -9753': ['Anna', 'Holden Cafield'} 'Karenina'], '987 -65 -4321': ['Yu', 'Tsun'], '123 -45 -6789': >>> 'Holden Cafield'} >>> employee['123 -45 -6789'] = 'Holden Caulfield' >>> employee {'100 -01 -0010': ['Hans', 'Castorp'], '864 -20 -9753': ['Anna', 'Karenina'], '987 -65 -4321': ['Yu', 'Tsun'], '123 -45 -6789': 'Holden Caulfield’} >>> employee = {[1, 2]: 1, [2, 3]: 3} Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> employee = {[1, 2]: 1, [2, 3]: 3} Type. Error: unhashable type: 'list'

Introduction to Computing Using Python Dictionary operators Class dict supports some of the same operators as class list >>> days = {'Mo': 1, 'Tu': 2, 'W': 3} >>> days['Mo'] 1 >>> days['Th'] = 5 >>> days {'Mo': 1, 'Tu': 2, 'Th': 5, 'W': 3} >>> days['Th'] = 4 >>> days {'Mo': 1, 'Tu': 2, 'Th': 4, 'W': 3} >>> 'Fr' in days False >>> len(days) 4 Class dict does not support all the operators that class list supports • + and * for example

Introduction to Computing Using Python Dictionary methods Operation Explanation d. items() Returns a view of the (key, value) pairs in d d. keys() Returns a view of the keys of d d. pop(key) Removes the (key, value) pair with key from d and returns the value d. update(d 2) Adds the (key, value) pairs of dictionary d 2 to d d. values() Returns a view of the values of d The containers returned by d. items(), d. keys(), and d. values() (called views) can be iterated over >>> days {'Mo': 1, 'Tu': 2, 'Th': 4, 'W': 3} >>> days. pop('Tu') 2 >>> days {'Mo': 1, 'Th': 4, 'W': 3} >>> days 2 = {'Tu': 2, 'Fr': 5} >>> days. update(days 2) >>> days {'Fr': 5, 'W': 3, 'Th': 4, 'Mo': 1, 'Tu': 2} >>> days. items() dict_items([('Fr', 5), ('W', 3), ('Th', 4), ('Mo', 1), ('Tu', 2)]) >>> days. keys() dict_keys(['Fr', 'W', 'Th', 'Mo', 'Tu']) >>> vals = days. values() >>> vals dict_values([5, 3, 4, 1, 2]) >>> for val in vals: print(val, end=' ') 53412 >>>

Introduction to Computing Using Python Dictionary vs. multi-way if statement Uses of a dictionary: • • container with custom indexes alternative to the multi-way if statement def complete(abbreviation): 'returns day of the week corresponding to abbreviation' if abbreviation == 'Mo': return 'Monday' elif abbreviation == 'Tu': return 'Tuesday' elif. . . else: # abbreviation must be Su return 'Sunday' def complete(abbreviation): 'returns day of the week corresponding to abbreviation' days = {'Mo': 'Monday', 'Tu': 'Tuesday', 'We': 'Wednesday', 'Th': 'Thursday', 'Fr': 'Friday', 'Sa': 'Saturday', 'Su': 'Sunday'} return days[abbreviation]

Introduction to Computing Using Python Dictionary as a container of counters Uses of a dictionary: • • • container with custom indexes alternative to the multi-way if statement container of counters Problem: computing the number of occurrences of items in a list >>> grades = [95, 96, 100, 85, 90, 95, 100] >>> frequency(grades) {96: 1, 90: 1, 100: 3, 85: 1, 95: 3} >>> Solution: Iterate through the list and, for each grade, increment the counter corresponding to the grade. Problems: • impossible to create counters before seeing what’s in the list • how to store grade counters so a counter is accessible using the corresponding grade Solution: a dictionary mapping a grade (the key) to its counter (the value)

Introduction to Computing Using Python Dictionary as a container of counters Problem: computing the number of occurrences of items in a list >>> grades = [95, 96, 100, 85, 90, 95, 100] ���� counters 95 96 100 85 90 1 2 3 1 1 def frequency(item. List): 'returns frequency of items in item. List' counters = {} for item in item. List: if item in counters: # increment item counters[item] += 1 else: # create item counters[item] = 1 return counters

Introduction to Computing Using Python Exercise Implement function wordcount() that takes as input a text—as a string— and prints the frequency of each word in the text; assume there is no punctuation in the text. def word. Count(text): 'prints frequency of each word in text' >>> text = 'all animals are equal but some animals are more equal than other' >>> word. Count(text) word. List = text. split() # split text into list of words all def appears 1 time. num. Chars(filename): animals appears times. counters ={} the 2 number # dictionary of counters 'returns of characters in filename' some appears 1 time. for word in word. List: equalif word appears 2 times. # counter in counters: infile = open(filename, 'r') for word exists but appears 1 time. counters[word] += 1 content = infile. read() otherelse: appears 1 time. infile. close() # counter for word doesn't exist are appears 2 times. = 1 counters[word] than return appears 1 time. len(content) more appears 1 time. # print word counts for word in counters: >>> if counters[word] == 1: print('{: 8} appears {} time. '. format(word, counters[word])) else: print('{: 8} appears {} times. '. format(word, counters[word]))

Introduction to Computing Using Python Built-in class tuple The class tuple is the same as class list … except that it is immutable >>> lst = ['one', 'two', 3] >>> lst[2] 3 >>> lst[2] = 'three' >>> lst ['one', 'two', 'three'] >>> tpl = ('one', 'two', 3) >>> tpl[2] 3 >>> tpl[2] = 'three' Traceback (most recent call last): File "<pyshell#131>", line 1, in <module> tpl[2] = 'three' Type. Error: 'tuple' object does not support item assignment >>> Why do we need it? Sometimes, we need to have an “immutable list”. • For example, when we need a dictionary that has lists as keys

Introduction to Computing Using Python Exercise Implement function lookup() that implements a phone book lookup application. Your function takes, as input, a dictionary representing a phone book, mappingtuples (containing the first and last name) to strings >>> phonebook = { (containing phone numbers) ('Anna', 'Karenina'): '(123)456 -78 -90', ('Yu', 'Tsun'): '(901)234 -56 -78', ('Hans', 'Castorp'): '(321)908 -76 -54'} def lookup(phonebook): >>> lookup(phonebook) '''implements interactive phone book service using the input Enter the first name: Anna phonebook dictionary''' Enter the last name: Karenina while True: (123)456 -78 -90 first = input('Enter the first name: ') Enter the first name: last = input('Enter the last name: ') person = (first, last) # construct the key if person in phonebook: # if key is in dictionary print(phonebook[person]) # print value else: # if key not in dictionary print('The name you entered is not known. ')

Introduction to Computing Using Python Modules, revisited A module is a file containing Python code. When the module is executed (imported), then the module is (also) a namespace. • This namespace has a name, typically the name of the module. • In this namespace live the names that are defined in the global scope of the module: the names of functions, values, and classes defined in the module. • These names are the module’s attributes. Built-in function dir() returns the names defined in a namespace >>> import math >>> dir(math) ['__doc__', '__file__', '__name__', '__package__', 'acosh', 'asinh', 'atan 2', 'atanh', 'ceil', 'copysign', 'cosh', 'degrees', 'erf', 'erfc', 'expm 1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log 10', 'log 1 p', 'modf', 'pi', 'pow', 'radians', 'sinh', 'sqrt', 'tanh', 'trunc’] >>> math. sqrt <built-in function sqrt> >>> math. pi To access the imported module’s attributes, 3. 141592653589793 the name of the namespace must be specified

Introduction to Computing Using Python Importing a module When the Python interpreter executes an import statement, it: 1. Looks for the file corresponding to the module to be imported. 2. Runs the module’s code to create the objects defined in the module. 3. Creates a namespace where the names of these objects will live. An import statement only lists a name, the name of the module • without any directory information or. py suffix. Python uses the Python search path to locate the module. • The search path is a list of directories where Python looks for modules. • The variable name path defined in the Standard Library module sys refers to this list. current working directory Standard Library folders >>> import sys >>> sys. path ['/Users/me', '/Library/Frameworks/Python. framework/Versions/3. 2/lib/python 32. zip', . . . '/Library/Frameworks/Python. framework/Versions/3. 2/lib/python 3. 2/site-packages'] >>>

Introduction to Computing Using Python The Python search path By just adding folder /Users/me to the search stored path, module example canthat be is not Suppose we want to import module example in folder /Users/me imported in list sys. path names in the shell namespace; notecontains that example is not in no folder in the Python search path module example >>> ================ RESTART ================ >>> dir() ['__builtins__', '__doc__', '__name__', '__package__'] >>> import example Traceback (most recent call last): File "<pyshell#79>", line 1, in <module> import example Import. Error: No module named example >>> import sys >>> sys. path. append('/Users/me') >>> import example >>> example. f <function f at 0 x 10278 dc 88> >>> example. x 0 >>> dir() ['__builtins__', '__doc__', '__name__', '__package__', 'example', 'sys’] 'an example module' def f(): 'function f' print('Executing f()') def g(): 'function g' print('Executing g()') x = 0 # global var When called without an argument, function dir() returns the names in the top-level module • the shell, in this case.

Introduction to Computing Using Python Three ways to import module attributes 'an example module' def f(): 'function f' print('Executing f()') 1. Import the (name of the) module >>> import example >>> example. x 0 >>> example. f <function f at 0 x 10278 dd 98> >>> example. f() Executing f() >>> def g(): 'function g' print('Executing g()') x = 0 # global var example. py f example g x module example namespace __main__ f() g() 0

Introduction to Computing Using Python Three ways to import module attributes 'an example module' def f(): 'function f' print('Executing f()') 2. Import specific module attributes >>> from example import f >>> f() Executing f() >>> x Traceback (most recent call last): File "<pyshell#28>", line 1, in <module> x Name. Error: name 'x' is not defined >>> def g(): 'function g' print('Executing g()') x = 0 # global var example. py f f g x module example namespace __main__ f() g() 0

Introduction to Computing Using Python Three ways to import module attributes 'an example module' def f(): 'function f' print('Executing f()') 3. Import all module attributes >>> from example import * >>> f() Executing f() >>> g() Executing g() >>> x 0 >>> f g def g(): 'function g' print('Executing g()') x = 0 # global var example. py x f g x module example namespace __main__ f() g() 0

Introduction to Computing Using Python A class is a namespace A class is really a namespace • The name of this namespace is the name of the class • The names defined in this namespace are the class attributes (e. g. , class methods) • The class attributes can be accessed using the standard namespace notation __add__ count >>> list. pop <method 'pop' of 'list' objects> >>> list. sort <method 'sort' of 'list' objects> >>> dir(list) ['__add__', '__class__', . . . 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] Function dir() can be used to list the class attributes pop x. . . namespace list __add__() count() pop() sort()

Introduction to Computing Using Python Class methods A class method is really a function defined in the class namespace; when Python executes instance. method(arg 1, lst. append(6) arg 2, …) lst. sort() it first translates it to class. method(instance, list. append(lst, 6) arg 1, arg 2, …) list. sort(lst) and actually executes this last statement The function has an extra argument, which is the object invoking the method __add__() count >>> lst = [9, 1, 8, 2, 7, 3] >>> lst. sort() >>> lst [1, 2, 3, 7, 8, 9] >>> lst = [9, 1, 8, 2, 7, 3] >>> lst [9, 1, 8, 2, 7, 3] >>> list. sort(lst) >>> lst [1, 2, 3, 7, 8, 9] >>> lst. append(6) >>> lst [1, 2, 3, 7, 8, 9, 6] >>> list. append(lst, 5) >>> lst [1, 2, 3, 7, 8, 9, 6, 5] pop x. . . namespace list count() pop() sort()

Introduction to Computing Using Python Exercise Rewrite the below Python statement so that instead of making the usual method invocations instance. method(arg 1, lst. append(6) arg 2, …) lst. sort() you use the notation class. method(instance, list. append(lst, 6) arg 1, arg 2, …) list. sort(lst) >>> s = 'hello' >>> s = 'ACM' >>> s. lower() 'acm' >>> s. find('C') 1 >>> s. replace('AC', 'IB') 'IBM' >>> s = 'ACM' >>> str. lower(s) 'acm' >>> str. find(s, 'C') 1 >>> str. replace(s, 'AC', 'IB') 'IBM' >>>