Dictionary usage
The dictionary is useful in many ways. Each element in the dictionary has a key and a value. It is like the Pinyin and corresponding text in the modern Chinese dictionary. Keys in the dictionary are unique, but values are not necessarily unique. You can see how similar it is to the modern Chinese dictionary.
Functions used in the classic dictionary
Example of a simple phone book:
# 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])
Dictionary Method
Fromkeys: Creates a new dictionary for the specified key. The default value of each key is none.
{}. Fromkeys (['name', 'age'])
Get: a more relaxed Method for accessing dictionary items.
D. get ('name ')
# A simple database using get()# Insert database (people) from Listing 4-1 here.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:key = request # In case the request is neither 'p' nor 'a'if request == 'p': key = 'phone'if request == 'a': key = 'addr'# Use get to provide default values:person = people.get(name, {})label = labels.get(key, key)result = person.get(key, 'not available')print "%s's %s is %s." % (name, label, result)
Has_key: Check whether the dictionary contains the given key. D. haos_key (). Returns True or False.
Items: returns the list of all dictionary items.
Iteritems: The methods are roughly the same, but an iterator instead of a list is returned.
Keys: returns the keys in the dictionary as a list. (Note the differences between the differentiation and items)
Iterkeys: return the iterator for the key.
Pop: obtain the value of the corresponding key, and then delete the key-value pair.
Popitem: a random item is displayed,
Setdefault: You can get the value related to the given key, and set the corresponding key value without the key in the dictionary.
Update: update a dictionary.
d={'1':'d','2':'s','3':'a'}x={'1','jk'}d.update(x)
Values: returns the value in the dictionary in the form of a list.
Itervalues: the return value iterator.