See All Titles |
![]() ![]() Built-in MethodsTable 7.1 lists the methods for dictionary objects. The clear(), copy(), get(), and update() methods were added recently in Python 1.5. setdefault() was introduced in 2.0.
Below, we showcase some of the more common dictionary methods: >>> dict2 = { 'name': 'earth', 'port': 80 } >>> dict2.has_key('name') 1 >>> >>> dict2['name'] 'earth' >>> >>> dict2.has_key('number') 0 The has_key() method is Boolean, indicating whether the given key is valid for the dictionary the method is operating on. Attempting to access a non-existent key will result in an exception (KeyError) as we saw at the beginning of this chapter in Section 7.1. Mapping types do not support the in and not in operators as sequences do, so has_key() is our best bet. Other useful dictionary methods focus entirely on their keys and values. These are keys(), which returns a list of the dictionary's keys, values(), which returns a list of the dictionary's values, and items(), which returns a list of (key, value) tuple pairs. These are useful for when you wish to iterate through a dictionary's keys or values, albeit in no particular order. >>> dict2.keys() ['port', 'name'] >>> >>> dict2.values() [80, 'earth'] >>> >>> dict2.items() [('port', 80), ('name', 'earth')] >>> >>> for eachKey in dict2.keys(): … print 'dict2 key', eachKey, 'has value', dict2[eachKey] … dict2 key port has value 80 dict2 key name has value earth The keys() method is fairly useful when used in conjunction with a for loop to retrieve a dictionary's values as it returns a list of a dictionary's keys. However, because its items are unordered, imposing some type of order is usually desired. Below, we present the same the loop, but sort the keys (using the list's sort() method) before retrieval. >>> dict2Keys = dict2.keys() >>> dict2Keys.sort() >>> for eachKey in dict2Keys: … print 'dict2 key', eachKey, 'has value', dict2[eachKey] … dict2 key name has value earth dict2 key port has value 80 The update() method can be used to add the contents of one directory to another. Any existing entries with duplicate keys will be overridden by the new incoming entries. Non-existent ones will be added. All entries in a dictionary can be removed with the clear() method. >>> dict2= { 'host':'earth', 'port':80 } >>> dict3= { 'host':'venus', 'server':'http' } >>> dict2.update(dict3) >>> dict2 {'server': 'http', 'port': 80, 'host': 'venus'} >>> dict3.clear() >>> dict3 {} The copy() method simply returns a copy of a dictionary. Note that this is a shallow copy only. Again, see Section 6.19 regarding shallow and deep copies. Finally, the get() method is similar to using the key-lookup operator ( [ ] ), but allows you to provide a default value returned if a key does not exist. If a key does not exist and a default value is not given, then None is returned. This is a more flexible option than just using key-lookup because you do not have to worry about an exception being raised if a key does not exist. >>> dict4 = dict2.copy() >>> dict4 {'server': 'http', 'port': 80, 'host': 'venus'} >>> dict4.get('host') 'venus' >>> dict4.get('xxx') >>> type(dict4.get('xxx')) <type 'None'> >>> dict4.get('xxx', 'no such key') 'no such key' Python 2.0 introduces a new dictionary built-in method, setdefault(), which is intended on making code shorter by collapsing a common idiom: you want to check if a dictionary has a key. If it does, you want its value. If the dictionary does not have the key you are seeking, you want to set a default value and then return it. That is precisely what setdefault() does: >>> myDict = { 'host': 'earth', 'port': 80 } >>> myDict.keys() ['host', 'port'] >>> myDict.items() [('host', 'earth'), ('port', 80)] >>> myDict.setdefault('port', 8080) 80 >>> myDict.setdefault('prot', 'tcp') 'tcp' >>> myDict.items() [('prot', 'tcp'), ('host', 'earth'), ('port', 80)] For more information, take a look at the "What's New in 2.0" online document. The URL is available in the Online Resources section of the Appendix and on the CD-ROM.
|
© 2002, O'Reilly & Associates, Inc. |