Python Development Course
Chapter
>
Level

Using Dictionaries
Iterating over Dictionaries

Objective

Recover all materials in the field and run inventory of all collected items before putting them away in specific containers.

A storm wrecked the outpost by the bridge scattering materials everywhere, I’m sure those materials can be used for later. Run inventory or each of the objects you pick up and put them away in the storeroom across the bridge.

First collect all debris scattered in the field, those being: "branches" ,"boulders" and "planks" . Once you have collected all the items place them in a dictionary named materials and add all three (3) of the material names and quantities inside it.

materials = {} materials["branches"] = number of branches collected ......

Once everything is placed inside a dictionary, head for the light X mark and run inventory on all of the materials you’ve gathered using a for loop with the speak() function. Since dictionaries are different from lists you can’t loop through them in a sequence in the same way, instead dictionaries have their own method of pulling this off.

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

By setting up two variables, in this case name and number you can get the two fields in a dictionary. Using the in statement followed up by the name of the dictionary and the function items() you can iterate over the dictionary like a normal for loop.

After running inventory, walk to the dark X marks and store the materials you’ve gathered in the dictionary inside containers using the place() function, like this: player.place(materials["branches"]) . There are three (3) dark X marks, on the left container place the "branches" , in the middle container place the"boulders" and in the right container place the"planks" . Put everything away in the correct position in order to complete the level.

Code book