You’ve seen that lists are useful when you want to group values into a structure and refer to each value by number. In this chapter, you learn about a data structure in which you can refer to each value by name. This type of structure is called a mapping. The only built-in mapping type in Python is the dictionary. The values in a dictionary don’t have any particular order but are stored under a key, which may be a number, a string, or even a tuple. On the other hand, dictionaries—both real ones and their Python equivalent—are constructed so that you can look up a specific word (key) easily, to find
its definition (value).
A dictionary is more appropriate than a list in many situations. Here are some examples of uses of Python dictionaries:
>>> names = ['Alice', 'Beth', 'Cecil', 'Dee-Dee', 'Earl'] this is a list.
>>> numbers = ['2341', '9102', '3158', '0142', '5551'] this is a list.
What if you wanted to create a little database where you could store the telephone numbers of these people—how would you do that?
Once you’ve created these lists, you can look up Cecil’s telephone number as follows:
>>> numbers[names.index('Cecil')]
3158
Creating and Using Dictionaries
Dictionaries are written like this:
phonebook = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
Dictionaries consist of pairs (called items) of keys and their corresponding values. In this example, the names are the keys and the telephone numbers are the values. Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary (without any items) is written with just two curly braces, like this: {}
The dict Function
You can use the dict function1 to construct dictionaries from other mappings (for example, other dictionaries) or from sequences of (key, value) pairs:
>>> items = [('name', 'Gumby'), ('age', 42)]
>>> d = dict(items)
>>> d
{'age': 42, 'name': 'Gumby'}
>>> d['name']
'Gumby'
It can also be used with keyword arguments, as follows:
>>> d = dict(name='Gumby', age=42)
>>> d
{'age': 42, 'name': 'Gumby'}
Although this is probably the most useful application of dict, you can also use it with a mapping argument to create a dictionary with the same items as the mapping.
Basic Dictionary Operations
The basic behavior of a dictionary in many ways mirrors that of a sequence:
• len(d) returns the number of items (key-value pairs) in d.
• d[k] returns the value associated with the key k.
• d[k] = v associates the value v with the key k.
• del d[k] deletes the item with key k.
• k in d checks whether there is an item in d that has the key k.
Although dictionaries and lists share several common characteristics, there are some
important distinctions:
Key types: Dictionary keys don’t have to be integers (though they may be). They may be any immutable type, such as floating-point (real) numbers, strings, or tuples.
Automatic addition: You can assign a value to a key, even if that key isn’t in the dictionary to begin with; in that case, a new item will be created. You cannot assign a value to an index outside the list’s range (without using append or something like that).
Membership: The expression k in d (where d is a dictionary) looks for a key, not a value. The expression v in l, on the other hand (where l is a list) looks for a value, not an index.
Note: The dict function isn’t really a function at all. It is a type, just like list, tuple, and str.
The first point—that the keys may be of any immutable type—is the main strength of dictionaries.
The second point is important, too. Just look at the difference here:
>>> x = []
>>> x[42] = 'Foobar'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IndexError: list assignment index out of range
>>> x = {}
>>> x[42] = 'Foobar'
>>> x
{42: 'Foobar'}
Dictionary.py Example
# A simple database
# A dictionary with person names as keys. Each person is represented as
# another dictionary with the keys 'phone' and 'addr' referring to their phone
# number and address, respectively.
people = {
'Alice': {
'phone': '2341',
'addr': 'Foo drive 23'
},
'Beth': {
'phone': '9102',
'addr': 'Bar street 42'
},
'Cecil': {
'phone': '3158',
'addr': 'Baz avenue 90'
}
}
# Descriptive labels for the phone number and address. These will be used
# when printing the output.
labels = {
'phone': 'phone number',
'addr': 'address'
}
name = raw_input('Name: ')
# Are we looking for a phone number or an address?
request = raw_input('Phone number (p) or address (a)? ')
# Use the correct key:
if request == 'p': key = 'phone'
if request == 'a': key = 'addr'
# Only try to print information if the name is a valid key in
# our dictionary:
if name in people: print "%s's %s is %s." % \
(name, labels[key], people[name][key])
Here is a sample run of the program:
Name: Beth
Phone number (p) or address (a)? p
Beth's phone number is 9102.
String Formatting with Dictionaries
If you use a dictionary (with only strings as keys) instead of a tuple, you can make the string
formatting even snazzier. After the % character in each conversion specifier, you add a key
(enclosed in parentheses), which is followed by the other specifier elements:
>>> phonebook
{'Beth': '9102', 'Alice': '2341', 'Cecil': '3258'}
>>> "Cecil's phone number is %(Cecil)s." % phonebook
"Cecil's phone number is 3258."
Thursday, March 1, 2018
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment