Python Learning notes: an example of using a dictionary

Source: Internet
Author: User
Classic Dictionary Use functions
Dict: A dictionary is created by a sequence of other mappings (such as other dictionaries) or (keys, values). Of course dict becomes a function is not very exact, it is essentially a type. Like a list.

The code is as follows:


items=[(' name ', ' Zhang '), (' Age ', 42)]
D=dict (items)
d[' name ']

Len (d): Returns the number of items
D[K]: Returns the value above the key K.
D[K]=V: Sets the value of K to K.
Del D[k]: Delete this item in the dictionary.
K in D: Check if D contains an entry with a key of K. Note: You can only look up keys and not look up values.
Simple Phone This example:

The code is as follows:


# A Simple Database
# A dictionary with the 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'll be used
# when printing the output.
Labels = {
' Phone ': ' Phone number ',
' Addr ': ' Address '
}
Name = Raw_input (' Name: ')
# is 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 was a valid key in
# Our Dictionary:
If name in People:print "%s ' s%s" is%s. "% \
(name, Labels[key], People[name][key])

Dictionary methods
Clear: Clears all items in the dictionary.

The code is as follows:


X.clear ()

Copy: Shallow copy dictionary.

The code is as follows:


Y=x.copy ()

Deepcopy: Also copy, to see the difference from copy.

The 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, and the default corresponding value for each key is none.

The code is as follows:


{}.fromkeys ([' Name ', ' age '])


Get: A more relaxed way to access dictionary entries.

The code is as follows:


D.get (' name ')


The code is as follows:


# A Simple database using Get ()
# Insert Database (people) from Listing 4-1.
Labels = {
' Phone ': ' Phone number ',
' Addr ': ' Address '
}
Name = Raw_input (' Name: ')
# is 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 is%s. '% (name, label, result)

Has_key: Checks whether the dictionary contains the given key. D.haos_key (). The value returns True, False.

Items: Returns all dictionary items as a list.

Iteritems: The method is approximately the same, but returns an iterator instead of a list.

Keys: Returns the keys in the dictionary as a list. (Note the distinction between items)

Iterkeys: Returns an iterator for the key.

Pop: Gets the value corresponding to the given key, and then deletes the key-value pair.

Popitem: pops up a random item,

SetDefault: You can get the value associated with a given key, and you can set the corresponding key value without the key in the dictionary.

Update: Updates another dictionary with one dictionary.

The code is as follows:


d={' 1 ': ' d ', ' 2 ': ' s ', ' 3 ': ' A '}
x={' 1 ', ' JK '}
D.update (x)

Values: Returns the value in the dictionary as a list.

Itervalues: Returns a worthwhile iterator.

  • 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.