Game Development Reference
In-Depth Information
apples
42
cats
>>>
As you can see, if you just use a dictionary in a for loop, the variable i will take on the
values of the dictionary's keys, not its values. But if you have the dictionary and the key,
you can get the value as we do above with favorites[i] . But remember that because
dictionaries are unordered, you cannot predict which order the for loop will execute in.
Above, we typed the 'animal' key as coming before the 'number' key, but the for
loop printed out 'number' before 'animal' .
Dictionaries also have two useful methods, keys() and values() . These will return
values of a type called dict_keys and dict_values , respectively. Those data types
are beyond the scope of this topic, but you can easily convert them to lists with the list()
function (just like str() converts a value to a string value.) Then you will have an ordered
list of the key values and the value values in the dictionary value. Try typing the following
into the shell:
>>> favorites = {'fruit':'apples', 'animal':'cats',
'number':42}
>>> list(favorites.keys())
['fruit', 'number', 'animal']
>>> list(favorites.values())
['apples', 42, 'cats']
>>>
Using these methods to get a list of the keys and values that are in a dictionary can be
very helpful. Do not forget to convert the return value of dict_keys and dict_keys
with the dict_keys function first, otherwise you may get errors in your program.
Sets of Words for Hangman
We will make changes to our original Hangman program. These changes can be
downloaded from http://inventwithpython.com/hangman2.py
So how can we use dictionaries in our game? First, let's change the list words into a
dictionary whose keys are strings and values are lists of strings. (Remember that the string
method split() evaluates to a list.
59. words = {'Colors':'red orange yellow green blue indigo
violet white black brown'.split(),
 
Search WWH ::




Custom Search