Page 51 - Programming the Raspberry Pi Getting Started with Python
P. 51
problem, experiment with the built-in function lower. You can look at a corrected version in the file
4_8_hangman_full_solution.py.
Dictionaries
Lists are great when you want to access your data starting at the beginning and working your way
through, but they can be slow and inefficient when they get large and you have a lot of data to trawl
through (for example, looking for a particular entry). It’s a bit like having a book with no index or
table of contents. To find what you want, you have to read through the whole thing.
Dictionaries, as you might guess, provide a more efficient means of accessing a data structure when
you want to go straight to an item of interest. When you use a dictionary, you associate a value with a
key. Whenever you want that value, you ask for it using the key. It’s a little bit like how a variable
name has a value associated with it; however, the difference is that with a dictionary, the keys and
values are created while the program is running.
Let’s look at an example:
This example is concerned with recording the number of eggs each of my chickens is currently
laying. Associated with each chicken’s name is a number of eggs per week. When we want to retrieve
the value for one of the hens (let’s say Penny), we use that name in square brackets instead of the
index number that we would use with a list. We can use the same syntax in assignments to change one
of the values.
For example, if Bernadette were to a lay an egg, we could update our records by doing this:
You may have noticed that when the dictionary is printed, the items in it are not in the same order
as we defined them. The dictionary does not keep track of the order in which items were defined. Also
note that although we have used a string as the key and a number as the value, the key could be a
string, a number, or a tuple (see the next section), but the value could be anything, including a list or
another dictionary.
Tuples
On the face of it, tuples look just like lists, but without the square brackets. Therefore, we can define
and access a tuple like this:
However, if we try to change an element of a tuple, we get an error message, like this one:
The reason for this error message is that tuples are immutable, meaning that you cannot change
them. Strings and numbers are the same. Although you can change a variable to refer to a different
string, number, or tuple, you cannot change the number itself. On the other hand, if the variable
references a list, you could alter that list by adding, removing, or changing elements in it.