Python study notes (10) -- combined data type (dictionary type)

Understand the mapping:

A map is a correspondence between keys (indexes) and values ​​(data). A dictionary is a collection of key-value pairs that are unordered. Use curly brackets to represent {}, and dict() to create, key-value pairs are represented by colon:.

{key:value, key:value, key:value}
>>> d={ " China " : " Beijing " , " US " : " Washington " , " UK " : " London " }
 >>> d
{ ' China ' : ' Beijing ' , ' US ' : ' Washington ' , ' UK ' : ' London ' }
 >>> d[ " China " ]
 ' Beijing ' 
>>> de={}     ''' Define an empty dictionary ''' 
>>> type(de)
 <class ' dict ' >

{} is used to generate an empty dictionary type. If the set type is empty, you need to use the set function instead of {}.

The processing method of the dictionary type:

del d[k] deletes the data value corresponding to k in dictionary d.

k in d whether a key is in dictionary d

d.keys() returns all key information in dictionary d

d.values() returns all value information in dictionary d

d.items() returns information about all key-value pairs in dictionary d

>>> "中国" in d
True
>>> d.keys()
dict_keys([ ' China ' , ' US ' , ' UK ' ])  
 >>> d.values
 ​​<built- in method values ​​of dict object at 0x0000000003011828 >
>>> d.values()
dict_values([ ' Beijing ' , ' Washington ' , ' London ' ]) / The returned value is not a list type, which can be traversed by for in, but cannot be treated as a list type
 >>> d.items()
dict_items([( ' China ' , ' Beijing ' ), ( ' US ' , ' Washington ' ), ( ' UK ' , ' London ' )])
 >>> del d[ " China " ]
 >>> d
{ ' US ' : ' Washington ' , ' UK ' : ' London ' }

d.get(k,<default>) If the key k exists, it will return the corresponding value, otherwise it will return the default value

d.pop(k,<default>) If the key k exists, take out the corresponding value, delete the corresponding key-value pair, and return the default value if it does not exist

d.popitem() randomly takes a key-value pair from dictionary d and returns it as a tuple

d.clear() deletes all key-value pairs.

len(d) returns the number of elements in d

>>> d={}
>>> d["type"]=2
>>> d["value"]=90
>>> d
{'type': 2, 'value': 90}

The application scenario of the dictionary: the expression of the map

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325296526&siteId=291194637