Introduction to Computing Using Python Dictionaries Userdefined Indexes

  • Slides: 17
Download presentation
Introduction to Computing Using Python Dictionaries User-defined Indexes

Introduction to Computing Using Python Dictionaries User-defined Indexes

Introduction to Computing Using Python User-defined indexes and dictionaries Goal: a container of employee

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

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'], '987 -65 -4321': ['Yu', 'Tsun'], '100 -01 -0010': ['Hans', 'Castorp']} >>> employee {'100 -01 -0010': ['Hans', 'Castorp'], '864 -209753': ['Anna', 'Karenina'], '987 -65 -4321': ['Yu', 'Tsun']} >>> employee['123 -45 -6789'] = 'Holden Cafield' >>> employee {'100 -01 -0010': ['Hans', 'Castorp'], '864 -209753': ['Anna', '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>>> employee = {[1, 2]: 1, [2, 3]: 3} 9753': ['Anna', 'Karenina'], '987 -65 -4321': Traceback (most recent call last): ['Yu', 'Tsun'], '123 -45 -6789': 'Holden File "<pyshell#2>", line 1, in <module> Caulfield’} 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

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

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=' ') 5 3 4 1 2 >>>

Introduction to Computing Using Python Dictionary vs. multi-way if statement Uses of a dictionary:

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

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

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

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. List word. Count(text) = text. split() # split text into list of words all def num. Chars(filename): appears 1 time. animals appears 2 times. counters ={} the dictionary in of file counters 'returns number of# characters filename' somefor word appears 1 time. in word. List: equal infile appears 2 counters: times. if word= in # counter for word exists open(filename, 'r') but appears time. counters[word] += 1 content = 1 infile. read() other infile. close() appears 1 time. else: # counter for word doesn't exist are appears 2 times. counters[word] = 1 than appears 1 time. return len(content) morefor word appears 1 time. in counters: # print word counts >>> 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 Exercise Implement function lookup() that implements a phone book

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. ')

Dict Comprehensions in Python By Dr. Ziad Al-Sharif

Dict Comprehensions in Python By Dr. Ziad Al-Sharif

Remember Comprehensions • Syntax expr for item in iterable if condition expr 1 if

Remember Comprehensions • Syntax expr for item in iterable if condition expr 1 if condition else expr 2 for item in iterable >>> grades = [95, 96, 100, 85, 90, 95, 100] >>> L = [ x+1 for x in grades if x<100] >>> L [96, 97, 86, 91, 96] >>> L = [ x+1 if x<100 else x for x in grades] >>> L [96, 97, 100, 86, 91, 96, 100] >>>

Remember Comprehensions • Syntax expr 1 if cond 1 else expr 2 for item

Remember Comprehensions • Syntax expr 1 if cond 1 else expr 2 for item in iterable if cond 2 >>> grades = [95, 96, 100, 85, 90, 95, 100] >>> L = [ x+2 if x<90 else x+1 for x in grades if x<100] >>> L [96, 97, 87, 96, 91, 96] >>>

Dict Comprehensions • Semantics >>> >>> {0: >>> d = dict() for i in

Dict Comprehensions • Semantics >>> >>> {0: >>> d = dict() for i in range(4): d[i] = chr(65+i) d 'A', 1: 'B', 2: 'C', 3: 'D'} is semantically equivalent to: >>> dict([(i, chr(65+i)) for i in range(4)]) {0: 'A', 1: 'B', 2: 'C', 3: 'D'} >>> is semantically equivalent to: >>> {i : chr(65+i) for i in range(4)}

Examples >>> d 1 = {i: chr(65+i) for i in range(4)} >>> d 1

Examples >>> d 1 = {i: chr(65+i) for i in range(4)} >>> d 1 {0 : 'A', 1 : 'B', 2 : 'C', 3 : 'D'} >>> d 2 = {k+1: v for k, v in d 1. items()} >>> d 2 {1: 'A', 2: 'B', 3: 'C', 4: 'D'} >>> d 3 = {k: v. lower() for k, v in d 2. items()} {1: 'a', 2: 'b', 3: 'c', 4: 'd'} >>>

Examples >>> def invert(d): . . . return {v : k for k, v

Examples >>> def invert(d): . . . return {v : k for k, v in d. items()}. . . >>> d = {0 : 'A', 1 : 'B', 2 : 'C', 3 : 'D'} >>> invert(d) {'A' : 0, 'B' : 1, 'C' : 2, 'D' : 3} >>> d = {(k, v): k+v for k in range(4) for v in range(4)} >>> d {(0, 0): (1, 0): (2, 0): (3, 0): } >>> 0, 1, 2, 3, (0, (1, (2, (3, 1): 1): 1, 2, 3, 4, (0, (1, (2, (3, 2): 2): 2, 3, 4, 5, (0, (1, (2, (3, 3): 3): 3, 4, 5, 6

Dict Comprehensions • PEP 202 introduces a syntactical extension to Python called the "list

Dict Comprehensions • PEP 202 introduces a syntactical extension to Python called the "list comprehension". • https: //www. python. org/dev/peps/pep-0202/ • PEP 274 proposes a similar syntactical extension called the "dictionary comprehension" or "dict comprehension" for short. • https: //www. python. org/dev/peps/pep-0274/ • You can use dict comprehensions in ways very similar to list comprehensions, • except that they produce Python dictionary objects instead of list objects.