Python9: Dictionary

Source: Internet
Author: User
Tags iterable shallow copy

Map is a type of mapping in Python and is a mutable object used to map one value to another value. The values in the map do not have a special order, they correspond to a key, and key can be a number, a string, or a tuple (that is, an immutable type).

Note that when key is a number, use the principle that if the value of the two numbers is equal (for example, 1 and 1.0), they are used for the same entry (but note that because the computer stores floating-point types as an approximation, using a floating-point type as key is not a sensible choice).

Construct a dictionary

You can construct a dictionary in the following ways:

>>> {4098: ' Jack ', 4127: ' Sjoerd '}{4098: ' Jack ', 4127: ' Sjoerd '}>>> {' Jack ': 4098, ' sjoerd ': 4127}{' jac K ': 4098, ' sjoerd ': 4127}>>> {' Alice ': ' 2341 ', ' Beth ': ' 9102 ', ' Cecil ': ' 3258 '} {' Beth ': ' 9102 ', ' Cecil ': ' 3258 ', ' Alice ': ' 2341 '}
The key and the value are separated by a colon, and the items are separated by commas. You can also use the Dict constructor:

The dictionary creation rules are as follows:

1) If the argument is empty, an empty dictionary is created;

>>> dict () {}
2) If a Dictionary object is passed in, a dictionary with the same key-value pair is created;

>>> phonebook = {' Alice ': ' 2341 ', ' Beth ': ' 9102 ', ' Cecil ': ' 3258 '}>>> dict (phonebook) {' Beth ': ' 9102 ', ' Cecil ': ' 3258 ', ' Alice ': ' 2341 '}
3) If the Iterable object is passed in, then each element of the object is required to be a Iterable object with two values, the first value of each object as key, and the second value as value, and if a key appears multiple times, Then the value corresponding to the last key will be the value of the key;

>>> Dict ([(1,123), (2,234), (3,345)]) {1:123, 2:234, 3:345}>>> dict ([(1,123), (2,234), (3,345), (2,890 )]) {1:123, 2:890, 3:345}
4) If the Kwarg value is given, then Kwarg will be added to the dictionary created in the first 3 steps, and if the key in the Kwarg already exists in the dictionary, the value of the key will replace the value of the same key in the dictionary.

>>> dict ([' Zero ', ' W '), (' 3 ', ' four '), one=1, two=2, three=3) {' Three ': 3, ' one ': 1, ' 3 ': ' t ', ' both ': 2, ' zero ': ' W '}
The following uses Dict to create an identical dictionary {"One": 1, "two": 2, "three": 3}:

>>> a = Dict (one=1, two=2, three=3) >>> B = {' One ': 1, ' both ': 2, ' three ': 3}>>> c = dict (Zip ([' O Ne ', ' both ', ' three '], [1, 2, 3]) >>> d = dict ([' One ', 1), (' Three ', 3)]) >>> e = dict ({' thre E ': 3, ' one ': 1, ' both ': 2} ' >>> a = = b = = C = = d = = Etrue

Basic operation of the dictionary

The following are the basic operations supported in the dictionary.

Len (d)

Returns the number of dictionary elements.

D[key]

Returns the value corresponding to key, or throws a Keyerror exception if key is not in the map.
The __missing__ () method can be defined in the subclass of the dictionary, and if the key does not exist, the D[key] operation will call the method, and the key as the parameter, see the following example:

>>> class Counter (dict):d ef __missing__ (Self, key): return 0>>> C = Counter () >>> c[' Red ']0 >>> c[' red '] + = 1>>> c[' red ']1>>> c[' green ']0

D[key] = value

Sets the value of the key to values.

Del D[key]

Remove D[key], throws Keyerror if key is not in the dictionary.

Key in D

Returns true if D has a key key, otherwise false is returned.

Key not in D

Equivalent to not a key in D.

ITER (d)

The iterator that returns the keys of D, which is the equivalent of ITER (D.keys ()).

Clear ()

Removes all entries in the dictionary.

Copy ()

Returns a shallow copy of the dictionary.

Classmethod Fromkeys (seq[, value])

Create a new dictionary, key from Seq,value from value. If you do not pass in value, the default value is None.

Get (key[, default])

Returns the value corresponding to key, returns default if key does not exist, or none if default is not provided.

Pop (key[, default])

If key is in the dictionary, remove key and return the value corresponding to key, otherwise return default. If default is not provided and key is not in the dictionary, Keyerror is thrown.

Popitem ()

Removes and returns any pair (key, value) in the dictionary. If the dictionary is empty, Keyerror is thrown.

SetDefault (key[, default])

If key is in the dictionary, its value is returned; otherwise, a key is inserted, the value default is used, and the default is returned. Default defaults to None.

Update ([other])

Use other to update the dictionary to overwrite the existing key. Other can be another dictionary or an iterator with key/value pairs.

Items ()

Returns the view ((Key,value) pair) of the entry for a dictionary.

Keys ()

Returns the view of the dictionary key.

VALUES ()

Returns a view of the value of the dictionary.

The views returned by the items (), keys (), and values () can have the following actions.

Operation of the Dictionary view

Items (), keys (), and values () return a dynamic view that reflects the changes in the dictionary, the view supports iterations, and supports the following methods:

Len (Dictview)

Returns the length of the view.

ITER (Dictview)

Returns an iterator to the view, in which the order of the iterations is arbitrary and relies on the history of the dictionary data manipulation.
Note During the iteration view, the dictionary performs an add or delete operation that causes runtimeerror or does not iterate over the entire data.

X in Dictview

Returns True if X is in the view.

Format a string with a dictionary

Python supports the use of dictionary (key,value) pairs to format strings, as shown in the following example:

>>> dishes = {' eggs ': 2, ' sausage ': 1, ' bacon ': 1, ' spam ': 500}>>> ' I has% (eggs) eggs. "% dishes ' I has< C0/>2.000000e+00ggs. '
This method is very common in template files.

Python9: Dictionary

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.