Game Development Reference
In-Depth Information
9 - Hangman
>>>
As you can see, the expression
favorites1 == favorites2
evaluates to
True
because dictionaries are unordered, and they are considered to be the same if they have the
same key-value pairs in them. Lists are ordered, so a list with the same values in them but
in a different order are not the same. Try typing this into the shell:
>>> listFavs1 = ['apples', 'cats', 42]
>>> listFavs2 = ['cats', 42, 'apples']
>>> listFavs1 == listFavs2
False
>>>
As you can see, the two lists
listFavs1
and
listFavs2
are not considered to be the
same because order matters in lists.
You can also use integers as the keys for dictionaries. Dictionaries can have keys of any
data type, not just strings. But remember, because
0
and
'0'
are different values, they will
be different keys. Try typing this into the shell:
>>> myDict = {'0':'a string', 0:'an integer'}
>>> myDict[0]
'an integer'
>>> myDict['0']
'a string'
>>>
You might think that using a
for
loop is hard with dictionaries because they do not have
integer indexes. But actually, it's easy. Try typing the following into the shell. (Here's a
hint, in IDLE, you do not have to type spaces to start a new block. IDLE does it for you. To
end the block, just insert a blank line by just hitting the Enter key. Or you could start a new
file, type in this code, and then press F5 to run the program.)
>>> favorites = {'fruit':'apples', 'animal':'cats',
'number':42}
>>> for i in favorites:
... print(i)
fruit
number
animal
>>> for i in favorites:
... print(favorites[i])