Presentation is loading. Please wait.

Presentation is loading. Please wait.

COSC 1306 COMPUTER SCIENCE AND PROGRAMMING

Similar presentations


Presentation on theme: "COSC 1306 COMPUTER SCIENCE AND PROGRAMMING"— Presentation transcript:

1 COSC 1306 COMPUTER SCIENCE AND PROGRAMMING
Jehan-François Pâris Fall 2016 1 1

2 THE ONLINE BOOK CHAPTER XII DICTIONARIES

3 Motivation Suppose we have a list of phone numbers such as:
[[ 'CS', ' '],[ 'UHPD' : ' ']] or inventory of soda cans such as: [['Coke', 12], ['Diet Coke', 8], ['Coke Zero', 2]] Finding the phone number of UHPD or the number of cans of 'Coke Zero' we have in stock requires searching through the list Too slow

4 Dictionaries (I) Store pairs of entries called items { 'CS' : ' ', 'UHPD' : ' '} Each pair of entries contains A key A value Key and values are separated by a colon Pairs of entries are separated by commas Dictionary is enclosed within curly braces

5 Dictionaries (II) { 'CS' : '713-743-3350', 'UHPD' : '713-743-3333'}
Can also be built step by step: number = {} number['CS'] = ' ' number['UHPD'] = ' '

6 Accessing values If we have age = {'Alice' : 25, 'Bob': 28} then age['Alice'] is 25 and age['Bob'] is 28

7 A problem What is printed by the following program?
mydict = {"cat":12, "dog":6, "horse":23} print(mydict["dog"]) 12 6 23 Error

8 Dictionaries are mutable
>>> age = {'Alice' : 25, 'Bob' : 28} >>> saved = age >>> age['Bob'] = 29 >>> age {'Bob': 29, 'Alice': 25} >>> saved {'Bob': 29, 'Alice': 25}

9 Keys must be unique >>> age = {'Alice' : 25, 'Bob' : 28, 'Alice' : 26} >>> age {'Bob': 28, 'Alice': 26}

10 Operations on dictionaries
>>> age = {'Bob': 28, 'Alice': 26} >>> len(age) 2 >>>age['Bob'] += 1 >>>age {'Bob': 29, 'Alice': 26} >>>age['Bob'] + age ['Alice'] 55

11 Adding contents age = {} age['Alice'] = 25
Cannot do the same with lists alist=[] alist[10]= 5 # NO NO

12 Global dictionary methods
Arguments Description keys() none Returns a view of the keys in the dictionary values() Returns a view of the values in the dictionary items() Returns a view of the items (KV pairs) in the dictionary

13 Examples >>> age = {'Alice' : 25, 'Carol': 'twenty-two'}
>>> age.items() dict_items([ ('Alice', 25), ('Carol', 'twenty-two')]) >>> age.keys() dict_keys([ 'Alice', 'Carol']) age.values() dict_values([25, 'twenty-two'])

14 Views and lists (I) To represent mydictionary as a list of KV tuples
mydictionary.items() To get the keys mydictionary.keys() To get the values mydictionary.values() Cannot index these three representations They are views, no lists

15 Views and lists (II) Can convert view into lists of tuples
list() function age = {'Alice' : 25, 'Carol': 22} >>> age.items() dict_items([('Carol', 22), ('Alice', 25)]) >>> list(age.items()) [('Carol', 'twenty-two'), ('Alice', 25)]

16 More dictionary methods
Arguments Description get() key Returns value associated with the key or none otherwise update() KV pair Updates/adds a KV pair popitem() Returns value associated with the key and removes the KV pair from the list none Same for arbitrary KV pair

17 Updating dictionaries
>>> age = {'Alice': 26 , 'Carol' : 22} >>> age.update({'Bob' : 29}) >>> age {'Bob': 29, 'Carol': 22, 'Alice': 26} >>> age.update({'Carol' : 23}) >>> age {'Bob': 29, 'Carol': 23, 'Alice': 26} >>> age['Bob'] = 30 >>> age {'Bob': 30, 'Carol': 23, 'Alice': 26}

18 Returning a value >>> age = {'Bob': 29,'Liz': 23,'Ann': 26}
>>> age.get('Bob') 29 >>> age['Bob'] 29

19 Removing a specific item (I)
>>> a = {'Ann' : 24, 'Liz' : 'twenty-two'} >>> a {'Liz': 'twenty-two', 'Ann': 24} >>> a.pop('Liz') 'twenty-two' >>> a {'Ann': 24}

20 Removing a specific item (II)
>>> a.pop('Alice') 26 >>> a {} >>>

21 Remove a random item >>> age = {'Bob': 29, 'Liz': 22, 'Ann': 27} >>> age.popitem() ('Bob', 29) >>> age {'Liz': 22, 'Ann': 27} >>> age.popitem() ('Liz', 23) >>> age {'Ann': 27}

22 Traversing a dictionary
Suppose we have an inventory such as: cans = {'Coke':12, 'Diet Coke':8, 'Coke Zero' : 2} How can we compute the total number of cans we have? Must go through all items in the dictionary Can use for akey in cans.keys() to go though all keys

23 Example cans = {'Coke':12, 'Diet Coke':8, 'Coke Zero':2} total = 0
for akey in cans.keys() : total += cans[akey] print(total, 'cans of soft drink') will print 22 cans of soft drink

24 Algebra matrices A matrix such as 𝐴= 0 1 2 10 11 12 20 21 22
can be represented as a list of lists a=[[0, 1, 2],[10, 11, 12],[20, 21, 22]] with row and column indices starting at zero The element a[i][j] of list a then corresponds to the element 𝑎 𝑖𝑗 of the matrix

25 Sparse matrices (I) Consider a matrix like D= 1 0 0 0 1 0 0 0 1
that has few non-zero elements The conventional Python representation d = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] wastes a lot of space Becomes a problem for very large matrices

26 Sparse matrices (II) We could use a dictionary
that would only contains the non-zero elements of the matrix We would then use d[(i, i)] instead of d[i][i] to access the non-zero elements of the diagonal matrix

27 How to access all elements
d[(i, i)] only works for non-zero elements on the diagonal Use alternate version of get() method dict.get(key, alternate) where alternate specifies the value to return if key is not in dictionary dict d.get((i, j), 0) works for all elements of the matrix


Download ppt "COSC 1306 COMPUTER SCIENCE AND PROGRAMMING"

Similar presentations


Ads by Google