Python Learning Notes: dictionaries (dict) about content

Source: Internet
Author: User

A dictionary is the only type of mapping in Python. The hash value in the Mapping type Object (key: Key), and the object pointed to (values: value), is a one-to-many relationship, which is

The elements of the dictionary are divided into two parts, namely the key and the value, a key corresponding to a value, the key cannot be duplicated, and the value can be repeated.


1. Create a dictionary.

(1). The dictionary uses curly braces ({}) to contain elements, and basic creation is a direct assignment, the key cannot be a tuple or a list, but the value can be.

>>> D = {' A ': 1, ' B ': 2, ' C ': 3}<span style= "White-space:pre" ></span>>>> d{' a ': 1, ' B ': 2, ' C ' : 3}>>> D = {' A ':(), ' B ': [1,2,3]}<span style= ' White-space:pre ' ></span> #值为元组, list >>> D{' A ': (1, 2, 3), ' B ': [1, 2, 3]}>>> D = {[1,2]:1}<span style= ' White-space:pre ' ></span> #键为列表, exception trace Back (most recent):  File "<pyshell#9>", line 1, in <module><span style= "White-space:pre" ></span>    D = {[1,2]:1}typeerror:unhashable type: ' List '


(2). Can be created with the Dict () function, a tuple (or list) is passed into the function, and the tuple (or list) contains multiple tuples (or lists) with corresponding relationships, and the function is automatically created as a dictionary type.

(Format: Dict () () () as long as it is able to express the corresponding relationship of the sequence can be)

>>> D = Dict (([' A ', 1],[' B ', 2])) <span style= "White-space:pre" ></span> #用元组, tuples with lists to express correspondence > >> d{' A ': 1, ' B ': 2}>>> D = Dict ([(' A ', 1), (' B ', 2)]) >>> d{' A ': 1, ' B ': 2}>>> type (D) <cl The ' dict ' >

(3) can use the Fromkeys () function to create, the function inside two parts of the content, one is the key, the second is the value, the key can be used in strings, tuples, lists, etc., the value can only be a value, and then the function

This value is assigned to all keys and the value does not exist by default to none. (Format: {}.fromkeys (Keys,value) keys are included in a sequence, and value is directly written up.)

>>> D = {}.fromkeys (' a ', ' B '), 2) <span style= "White-space:pre" ></span> #元组包含键 >>> d{' a ': 2, ' B ': 2}>>> D = {}.fromkeys ([' A ', ' B '],1) <span style= "White-space:pre" ></span> #列表包含键 >> > d{' a ': 1, ' B ': 1}>>> D = {}.fromkeys (' abc ', 1) <span style= "White-space:pre" ></span> #字符串包含键 >>> d{' A ': 1, ' B ': 1, ' C ': 1}>>> D = {}.fromkeys (' a ') <span style= "White-space:pre" ></span> #值默认为None >>> d{' a ': None}


2. Access the dictionary.

Because the dictionary is a mapping relationship, so there is no index value, the words you want to access can only be achieved by key, by key to find the corresponding value of the key, can not be found by the value of the key, is a one-to-one format.

>>> D = {' A ': 1, ' B ': 2, ' C ':3}>>> d{' a ': 1, ' B ': 2, ' C ': 3}>>> d[' a ']1>>> d[' B ']2>> ;> d[' C ']3


There is a relatively easy to confuse, the following looks like the index value to access, but this is not the case, at this time, is the key!
>>> D = {1: ' A ', 2: ' B ', 3: ' C '}>>> d{1: ' A ', 2: ' B ', 3: ' C '}>>> d[1] ' a ' >>> d[2] ' B ' >> ;> d[3] ' C '


3. Delete the dictionary.


A single delete dictionary element.

>>> D = {' A ': 1, ' B ': 2, ' C ':3}>>> d{' a ': 1, ' B ': 2, ' C ': 3}>>> del d[' a ']>>> d{' B ': 2, ' C ': 3}


The entire delete dictionary.

>>> D = {' A ': 1, ' B ': 2, ' C ':3}>>> d{' a ': 1, ' B ': 2, ' C ': 3}>>> del d>>> dtraceback (most Recent:  File "<pyshell#66>", line 1, in <module>    dnameerror:name ' are not defined

Empty the contents of the dictionary and let the dictionary become an empty dictionary.

>>> D = {' A ': 1, ' B ': 2, ' C ':3}>>> d{' a ': 1, ' B ': 2, ' C ': 3}>>> d.clear () >>> d{}


4. Update the dictionary.


A dictionary can be changed, just like a list.


Change the value of the dictionary.

>>> D = {' A ': 1, ' B ': 2, ' C ':3}>>> d{' a ': 1, ' B ': 2, ' C ': 3}>>> d[' a ']1>>> d[' a '] = 4>& Gt;> d{' A ': 4, ' B ': 2, ' C ': 3}

If the value of the dictionary is changed, the key does not exist and the key and value are added to the dictionary.

>>> D = {' A ': 1, ' B ': 2, ' C ':3}>>> d{' a ': 1, ' B ': 2, ' C ': 3}>>> d[' d '] = 4>>> d{' d ': 4, ' A ': 1, ' B ': 2, ' C ': 3}>>> d[' e '] = 0>>> d{' D ': 4, ' A ': 1, ' E ': 0, ' B ': 2, ' C ': 3}

5. About functions.

Len ()

Calculates the dictionary key-the number of values.

>>> D = {' A ': 1, ' B ': 2, ' C ':3}>>> d{' a ': 1, ' B ': 2, ' C ': 3}>>> len (D) 3

Get ()

The Get () function returns the value corresponding to the key in the dictionary dict, and returns the value of default if the key does not exist in the dictionary, and default defaults to None (format:dict.get (Key,default =none) )

>>> D = {' A ': 1, ' B ': 2, ' C ':3}>>> d{' a ': 1, ' B ': 2, ' C ': 3}>>> d.get (' a ') 1>>> d.get (' e ') >>> d.get (' E ', ten) 10>>> D

Items ()

The items () function returns a list containing the keys in the dictionary, the value pairs of tuples. (Format:dict.items () )

>>> D = {' A ': 1, ' B ': 2, ' C ':3}>>> d{' a ': 1, ' B ': 2, ' C ': 3}>>> D.items () dict_items ([' A ', 1], (' B ') , 2), (' C ', 3)])

Keys ()

The keys () function returns a list containing the keys in the dictionary. (Format:dict.keys () )

>>> D = {' A ': 1, ' B ': 2, ' C ':3}>>> d{' a ': 1, ' B ': 2, ' C ': 3}>>> D.keys () Dict_keys ([' A ', ' B ', ' C '])

VALUES ()

The values () function returns a list that contains all the values in the dictionary. (Format:dict.values () )

>>> D = {' A ': 1, ' B ': 2, ' C ':3}>>> d{' a ': 1, ' B ': 2, ' C ': 3}>>> d.values () dict_values ([1, 2, 3])

Pop ()

The pop () function removes the key in the dictionary and the corresponding value, and returns the value of default if the key does not exist, or an exception if default does not specify a value. (Format:dict.pop (key,default) )

>>> D = {' A ': 1, ' B ': 2, ' C ':3}>>> d{' a ': 1, ' B ': 2, ' C ': 3}>>> d.pop (' a ') 1>>> d{' B ': 2, ' C ': 3}>>> d.pop (' e ', 1) 1>>> D.pop (' F ') Traceback (most recent call last):  File "<pyshell#116 > ", Line 1, in <module>    D.pop (' F ') Keyerror: ' F '

Popitem ()

The Popitem () function randomly deletes and returns a pair of key values in the dictionary. (Format:dict.popitems () )

>>> D = {' A ': 1, ' B ': 2, ' C ':3}>>> d{' a ': 1, ' B ': 2, ' C ': 3}>>> d.popitem (' A ', 1)

SetDefault ()

The SetDefault () function finds the key in the dictionary dict, returns the value it corresponds to, returns the value of default if the key does not exist in the dictionary, and adds the key value to the dictionary, and default defaults to None.

(Format:dict.setdefault (key,default=none) )

>>> D = {' A ': 1, ' B ': 2, ' C ':3}>>> d{' a ': 1, ' B ': 2, ' C ': 3}>>> d.setdefault (' a ') 1>>> d{' A ': 1, ' B ': 2, ' C ': 3}>>> d.setdefault (' e ') >>> d{' A ': 1, ' e ': None, ' B ': 2, ' C ': 3}>>> d.setdef Ault (' F ', 5) 5

Update ()

The update () function adds the key value of the Dict2 to the original dictionary dict, whichever is the same if the same key is Dict2. (Format:dict.update (DICT2) )

>>> D = {' A ': 1, ' B ': 2, ' C ':3}>>> d{' a ': 1, ' B ': 2, ' C ': 3}>>> D1 = {' A ': 4, ' e ':5}>>> d1{' A ': 4, ' e ': 5}>>> d.update (D1) >>> d{' A ': 4, ' E ': 5, ' B ': 2, ' C ': 3}

Copy ()

The copy () function copies the contents of the Dict. (Format:dict.copy () )

>>> D = {' A ': 1, ' B ': 2, ' C ':3}>>> d{' a ': 1, ' B ': 2, ' C ': 3}>>> D1 = d.copy () >>> d1{' a ': 1 , ' B ': 2, ' C ': 3}


Python Learning Notes: dictionaries (dict) about content

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.