Creating a Dictionary
You need to create a lookup table where you associate values with keys.
Use a Python dictionary.
Arrays are great when you need to access a list of items in order, or you always know the index of the element that you want to use. Dictionaries are an alternative to lists for storing collections of data, but they are organized very differently.
Figure 6-1 shows how a dictionary is organized.
A dictionary stores key/value pairs in such a way that you can use the key to retrieve that value very efficiently and without having to search the whole dictionary.
To create a dictionary, you use the {} notation:
>>> phone_numbers = {‘Simon’:’01234 567899′, ‘Jane’:’01234 666666′} |
Discussion
In this example, the keys of the dictionary are strings, but they do not have to be; they could be numbers or in fact any data type, although strings are most commonly used.
The values can also be of any data type, including other dictionaries or lists. The following example creates one dictionary (a) and then uses it as a value in a second dictionary (b):
>>> a = {‘key1′:’value1’, ‘key2’:2} >>> a {‘key2’: 2, ‘key1’: ‘value1’} >>> b = {‘b_key1’:a} >>> b {‘b_key1’: {‘key2’: 2, ‘key1’: ‘value1’}} |
When you display the contents of a dictionary, you will notice that the order of the items in the dictionary may not match the order in which they were specified when the dictionary was created and initialized with some contents:
>>> phone_numbers = {‘Simon’:’01234 567899′, ‘Jane’:’01234 666666′} >>> phone_numbers {‘Jane’: ‘01234 666666’, ‘Simon’: ‘01234 567899’} |
Unlike lists, dictionaries have no concept of keeping items in order. Because of the way they are represented internally, the order of a dictionary’s contents will be—for all intents and purposes—random.
The reason the order appears to be random is that the underlying data structure that is a hash table. Hash tables use a hashing function to decide where to store the value; the hashing function calculates a numeric equivalent to any object.
You can find out more about hash tables at Wikipedia.
See Also
All the recipes between Recipes 6.12 and 6.15 involve the use of dictionaries.