Python learning notes: usage examples of dictionaries

Source: Internet
Author: User

Functions used in the classic dictionary
Dict: Create a dictionary through a sequence pair such as other ing (such as other dictionaries) or (Key, value. Of course, dict is not very definite as a function. It is essentially a type. Like list.

Copy codeThe Code is as follows:
Items = [('name', 'zhang '), ('age', 42)]
D = dict (items)
D ['name']

Len (d): number of returned items
D [k]: The value above the return key k.
D [k] = v: set the value of k to k.
Del d [k]: delete this item in the dictionary.
K in d: Check whether d contains k keys. Note: You can only search for keys, but not for values.
Example of a simple phone book:

Copy codeThe Code is as follows:
# A simple database
# A dictionary with person names as keys. Each person is represented
# Another dictionary with the keys 'phone' and 'addr' referring to their phone
# Number and address, respectively.
People = {
'Alice ':{
'Phone': '123 ',
'Addr ': 'foo drive 23'
},
'Beth ':{
'Phone': '123 ',
'Addr ': 'bar street 42'
},
'Cecil ':{
'Phone': '123 ',
'Addr ': 'baz avenue 90'
}
}
# Descriptive labels for the phone number and address. These will be used
# When printing the output.
Labels = {
'Phone': 'phone number ',
'Add': 'address'
}
Name = raw_input ('name :')
# Are we looking for a phone number or an address?
Request = raw_input ('phone number (p) or address ()? ')
# 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
Clear: clear all items in the dictionary.

Copy codeThe Code is as follows:
X. clear ()

Copy: A copy dictionary.

Copy codeThe Code is as follows:
Y = x. copy ()

Deepcopy: copy.

Copy codeThe Code is as follows:
From copy import deepcopy
D = {}
D ['names'] = ['as', 'sa']
C = d. copy ()
Dc = deepcopy (d)
D ['names']. append ('ad ')

Fromkeys: Creates a new dictionary for the specified key. The default value of each key is none.
Copy codeThe Code is as follows:
{}. Fromkeys (['name', 'age'])

Get: a more relaxed Method for accessing dictionary items.
Copy codeThe Code is as follows:
D. get ('name ')

Copy codeThe Code is as follows:
# A simple database using get ()
# Insert database (people) from Listing 4-1 here.
Labels = {
'Phone': 'phone number ',
'Add': 'address'
}
Name = raw_input ('name :')
# Are we looking for a phone number or an address?
Request = raw_input ('phone number (p) or address ()? ')
# 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.

Copy codeThe Code is as follows:
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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.