11 - Dictionaries

 1. Which of the following options creates a dictionary? Note: Dictionaries are created by specifying keys and values. You can also create an empty dictionary.
a) d = {}
b) d = {"john":40, "peter":45}
c) Both a and b create a dictionary
d) Neither a nor b apply 





 2. In the dictionary 'd' can you point out the keys?
d = {"jonathan":33, "Ruth":35}

  d is the only key

  jonathan, Ruth

  33, 35

  jonathan, 33, Ruth, 35

 3. Dictionaries make searching incredibly easy. Compare this to using a list and searching using a loop! Predict the output for the following:
mydictionary = {"jonathan":40, "peter":45}
"jonathan" in mydictionary


  False ("in" can be used to check if the key exists, but in this case it doesn't)

  True ("in" can be used to check if the key exists in the dictionary)


 4. Can you predict the output for the following:
d1 = {"score1":40, "score2":45}
d2 = {"score1":466, "score2":85}
d1 == d2





 5. The output here will be ____________ because d["score1"] is looking up the key 'score1' and will return the _____ stored in the dictionary for that key.
d = {"score1":40, "score2":45}

  40 / element

  40 / value

  40 / key

  score1 / key

 6. What does the following code do? (in relation to the dictionary myDict)
myDict = {'a':1,'b':2,'c':3,'d':4}
if 'a' in myDict: 
    del myDict['a']

  It deletes the entire dictionary

  It removes a key from a dictionary

  It removes all the values from the dictionary

  It duplicates the dictionary and then deletes the first copy

 7. To obtain the number of entries in a dictionary called 'd', which command would be used?
a) d.size()
b) len(d)
c) size(d)
d) d.len()





 8. Remember, dictionaries are perfect for when you have a key-value pair. What is the output here? #note that lists are defined in "[]"and tuples in "()". Tuples are considered immutable.
d = {"john":40, "peter":45}




  ['john', 'peter']

 9. Simply put, a mutable object can be changed after it is created, and an immutable object cannot. Fill in the blanks below.
Objects of built-in types like (int, float, bool, str, tuple, unicode) 
are __________. 
Objects of built-in types like (list, set, dict) are 

  immutable / fixed

  mutable / immutable

  immutable /mutable

  verifiable / mutable

 10. Analyse the code below which uses a dictionary and the 'count' command. What is the output? Remember you can go back to the 'code library' on to find code snippets on dictionaries.
def main():
    dictFilms = { 
       'Group 1' : (90, 90),
       'Group 2' : (44, 45),
       'Group 3' : (47, 90),
       'Group 4' : (90, 90),
       'Group 5' : (25, 23)  }

    for key in dictFilms:
        if dictFilms[key].count(90)>1:

    print("group(s) that have more than 1 occurence of a 90 score are:", my_list)


  ['Group 4', 'Group 5'])

  ['Group 1', 'Group 4'])

  ['Group 1', 'Group 2'])

  ['Group 3', 'Group 4'])