Storing and retrieving values

A dict is useful for storing and retrieving immutable objects and corresponding values, like product prices, for example. Here's a small game that uses a dict for this purpose:

choice = raw input("Choose scissors,

rock,

or paper: ")

results = {"scissors": "cut paper",

"rock":

: "crushes scissors",

"paper": "covers

rock"}

print choice, results[choice]

Here's one round of the game:

Choose scissors, rock, or paper: paper paper covers rock

You can also use if/elif/else statements for this purpose (see Chapter 10), but a dictionary is often better because it's built when a program first runs (which is more efficient) and it's easier to read if a lot of key:value pairs are involved. It's also easier to maintain and modify.

Was this article helpful?

0 0

Post a comment