Teacher's Guide

Chapter 8 / Level 6: Iterating over Dictionaries

Teaching Objective:

  • Student learns the syntax for iterating through a dictionary
  • Understands how it differs from iterating a list
  • Learns it’s applications and potential uses, the for loop being one example

Guide

In this exercise there are several materials scattered across the field that need to be picked up, categorized and put away. This is done by setting up a dictionary and using a for loop to iterate through it, then placing the individual parts in containers.

First walk through the field and collect all the materials scattered about, those being: "branches" ,"boulders" and "planks" . Place them inside a dictionary named materials and add to them the quantities you’ve collected.

materials = {}
materials["branches"] = 6
materials["boulders"] = 4
materials["planks"] = 5

Once all materials have been gathered and stored inside the dictionary, walk to the light X mark and use a for loop to iterate the dictionary using the speak() function.

for name, number in materials.items():
  player.speak("There were %d %s collected" % ( number, name))

Once the items have been categorized, walk towards the three (3) dark X marks and use the place() function to store each material in a specific container.

player.place(materials["branches"])
........
player.place(materials["boulders"])
........
player.place(materials["planks"])

On the left container place the "branches" materials, in the middle container place the"boulders" and in the right container place the"planks" materials. Put everything away in the correct position in order to complete the level.

Map overview and path

Map overview and path

Code Solution

import player

player.turn_left()
player.move_forward(5)
player.turn_right()
player.move_forward()
player.turn_left()
player.move_forward(3)
player.turn_left()
player.move_forward(3)
player.turn_left()
player.move_forward(8)
player.turn_left()
player.move_forward()
player.turn_left()
player.move_forward(3)
player.turn_left()
player.move_forward(7)
materials = {}
materials["branches"] = 6
materials["boulders"] = 4
materials["planks"] = 5
for name, number in materials.items():
  player.speak("There were %d %s collected" % ( number, name))
player.turn_left()
player.move_forward(2)
player.turn_right()
player.place(materials["branches"])
player.turn_right()
player.move_forward(3)
player.turn_left()
player.place(materials["boulders"])
player.turn_right()
player.move_forward(3)
player.turn_left()
player.place(materials["planks"])
Chapter 8 / Level 6: Iterating over Dictionaries | Teacher's Guide