CPSC120A
Fundamentals of Computer Science I

Activity 25

Dictionaries.

Dictionary Iteration

There are four different ways to iterate over the contents of a dictionary. In this activity you will explore a few of them.


For each of the following, describe what you expect the program to output.

  1.   my_dictionary = {"Smith": "120B", "Bouchard": "120A", "Shende": "250A"}
      for instructor in my_dictionary:
        if 'A' in my_dictionary[instructor]:
          print(instructor, end=',')
    
  2.   my_dictionary = {"Smith": "120B", "Bouchard": "120A", "Shende": "250A"}
      for instructor, course in my_dictionary.items():
        if '120' in course:
          print(instructor, end=',')
    
  3.   my_dictionary = {"Smith": "120B", "Bouchard": "120A", "Shende": "250A"}
      for instructor in my_dictionary:
        if '120' in my_dictionary[instructor]:
          del my_dictionary[instructor]
      print(my_dictionary)
    
  4.   value = '120B'
      key = ''
      my_dictionary = {"Smith": "120B", "Bouchard": "120A", "Shende": "250A"}
      for instructor, course in my_dictionary.items():
        if course == value:
          key = instructor
      print(key)