As a simple example of a dictionary, consider a phonebook. We could store phone numbers as tuples inside a list, with the first tuple element being the name of the person and the second tuple element being the phone number:
>>> phonelist = [('Fred','555-1231'),('Andy','555-1195'),('Sue','555-2193')]However, to find, say, Sue's phone number, we'd have to search each element of the list to find the tuple with Sue as the first element in order to find the number we wanted. With a dictionary, we can use the person's name as the index to the array. In this case, the index is usually refered to as a key. This makes it very easy to find the information we're looking for:
>>> phonedict = {'Fred':'555-1231','Andy':'555-1195','Sue':'555-2193'} >>> phonedict['Sue'] '555-2193'As the above example illustrates, we can initialize a dictionary with a comma-separated list of key/value pairs, separated by colons, and surrounded by curly braces. An empty dictionary can be expressed by a set of empty curly braces (
{}
).
Dictionary keys are not limited to strings, nor do all the keys of a dictionary need be of the same type. However, mutable objects such as lists can not be used as dictionary keys and an attempt to do so will raise a TypeError. To index a dictionary with multiple values, a tuple can be used:
>>> tupledict = {(7,3):21,(13,4):52,(18,5):90}Since the tuples used as keys in the dictionary consist of numbers, any tuple containing expressions resulting in the same numbers can be used to index the dictionary:
>>> tupledict[(4+3,2+1)] 21
In addition to initializing a dictionary as described above, you can add key/value pairs to a dictionary using assignment statements:
>>> tupledict[(19,5)] = 95 >>> tupledict[(14,2)] = 28To eliminate a key/value pair from a dictionary use the del statement.