Week 9 Quiz: Dictionaries (ThinkCSPY 12, lectures 9a, 9b)
dict-3-2: What is printed by the following statements? mydict = {"cat":12, "dog":6, "elephant":23, "bear":20} answer = mydict.get("cat") // mydict.get("dog") print(answer) (A) 2 (B) 0.5 (C) bear (D) Error, divide is not a valid operation on dictionaries.
(A) 2
dict-3-3: What is printed by the following statements? mydict = {"cat":12, "dog":6, "elephant":23, "bear":20} print("dog" in mydict) (A) True (B) False
(A) True Dog is a key in the dictionary
dict-3-5: What is printed by the following statements? total = 0 mydict = {"cat":12, "dog":6, "elephant":23, "bear":20} for akey in mydict: if len(akey) > 3: total = total + mydict[akey] print(total) (A) 18 (B) 43 (C) 0 (D) 61
(B) 43
dict-3-4: What is printed by the following statements? mydict = {"cat":12, "dog":6, "elephant":23, "bear":20} print(23 in mydict) (A) True (B) False
(B) False 23 is not a key in the dictionary (even though it is a value)
dict-3-1: What is printed by the following statements? mydict = {"cat":12, "dog":6, "elephant":23, "bear":20} keylist = list(mydict.keys()) keylist.sort() print(keylist[3]) (A) cat (B) dog (C) elephant (D) bear
(C) elephant Yes, the list of keys is sorted and the item at index 3 is printed.
immutable types OK for keys
- integers - strings - tuples?
How do you change a dictionary key:value pairs into a list of tuples?
.items() ex. inventory = {'apples': 430, 'bananas': 312, 'oranges': 525, 'pears': 217} print(list(inventory.items())) [('apples', 430), ('bananas', 312), ('oranges', 525), ('pears', 217)]
dictionary methods
.keys() .values() .items() .get() all of these use dot notation
How do you change a dictionary into a list of just the values?
.values() ex. inventory = {'apples': 430, 'bananas': 312, 'oranges': 525, 'pears': 217} print(list(inventory.values())) [430, 312, 525, 217]
What is a matrix? How to create?
A two dimensional collection Has rows and columns Create a list of lists, where each list is a column* so order is flipped: matrix = [[0, 0, 0, 1, 0], [0, 0, 0, 0, 0], [0, 2, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 3, 0]]
why are tuples useful?
Converting a dictionary to a list of tuples allows you to iterate through both the key an the value at the same time. for i, c in inventory.items(): print i+ c
how would you use a dict to represent a "sparse" matrix?
The keys are tuples with the row,column numbers. The values are the values. so matrix = [[0, 0, 0, 1, 0], [0, 0, 0, 0, 0], [0, 2, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 3, 0]] matrix_dict = {(0, 3): 1, (2,1): 2, (4,3): 3} * Now it's easier to access with indexing [ ]
True or False: you can omit the .keys() method when iterating over a dictionary?
True. Implicitly, the iteration will be over the dictionary keys
What is aliasing?
Whenever two variables refer to the same dictionary object You have to be careful because changes to one will affect the other: opposites = {'up': 'down', 'right': 'wrong', 'true': 'false'} alias = opposites print(alias is opposites) alias['right'] = 'left' print(opposites['right'])
get
a method that allows you to access the value associate with a key similar to the [ ] operator, but it will not cause a runtime error if the key is not present
How do you modify a dictionary and keep a copy of the original?
copy method: acopy = opposites.copy() acopy['right'] = 'left' #does not change opposites
How do you remove a key-value pair from a dictionary?
del statement **not a function..syntax: del inventory['pears']
how to add key:value pairs to a dict?
engirsh['one'] = 'uno' engrish['two'] = 'dos output: {'one':'uno', 'two':'dos'}
How to create an empty dict?
engrish = {}
How would you access 0's in a matrix? Can't use the dictionary
get method print(matrix.get(0, 3)))
How do you test if a key is in the dictionary?
in, not in operators
how to use get method
inventory = {'apples': 430, 'bananas': 312, 'oranges': 525, 'pears': 217} print(inventory.get("apples")) print(inventory.get("cherries")) print(inventory.get("cherries", 0)) >> 430 >> None >> 0
How would you create a list of all the keys of a dict?
ks = list(inventory.keys())
How to find the length of a dictionary?
len(dict_name)
mapping type (associative data collection) vs sequential type
mapping means an *unordered*, associative collection keys must be mutable, values can be anything
"sparse matrix"
one that is mostly made of 0s Not very efficient, so often it's better to use a dict
dict_name.keys()
returns a view of the keys in the dictionary You can: - iterate over the view of the keys, or - turn the keys into a list
dict-4-1: What is printed by the following statements? mydict = {"cat":12, "dog":6, "elephant":23, "bear":20} yourdict = mydict yourdict["elephant"] = 999 print(mydict["elephant"]) (A) 23 (B) None (C) 999 (D) Error, there are two different keys named elephant.
(C) 999 Correct! Yes, since yourdict is an alias for mydict, the value for the key elephant has been changed
dict-2-1: What is printed by the following statements? mydict = {"cat":12, "dog":6, "elephant":23} mydict["mouse"] = mydict["cat"] + mydict["dog"] print(mydict["mouse"]) (A) 12 (B) 0 (C) 18 (D) Error, there is no entry with mouse as the key.
C In this case, creates a new key 'mouse' and a value, which is the sum of 6 and 12.
What three compound data types are sequential collections?
strings, lists, tuples They are *ordered* from left to right
How to access / look up a corresponding value
value = enrish['one'] >> 'uno' *Note, the order will not matter, so you have to be specific about the key
mutability of dictionary
you can change the value (right hand side) by referencing the key (left hand side): inventory['pears'] = 0 # Sets the value for this key from whatever it was to 0.