The dictionary is represented by a = Dict (key:value) commonly used {} to represent the dictionary creation of a =dict (name= ' DEMONLG ') or a=dict{' name ': ' DEMONLG}
The dictionary is an unordered sequence, so the location of the print is not fixed, if you want to find an element can only be viewed through key, the same additions and deletions can only be done by key.
Type name |
Describe |
Examples Show |
Get
|
View |
Dict (' name ': ' 123 ') Dict.get (' name ') uses the GET command to look up the dictionary when no error is found in the dictionary |
DICT.[X] |
Check the dictionary, the dictionary has the element x can return, otherwise error |
Dict (' name ': ' 123 ') Dict (' age '), error returning program |
DICT.[X] |
The element corresponding to the primary key can be modified, and if the primary key does not exist, it can be added to the dictionary by adding the component element |
Dict (' name ': ' 123 ') Dict[' age '] = ' 13 '] if no such primary key is obtained {' name ': ' DEMONLG ', ' age ': ' 13 '} If you have this primary key, change the element of age to 13 |
Del Dict[x] |
Delete the element, delete the element only need to delete the corresponding component to delete the element, when the deleted element is not in the dictionary, return error |
a = { ' name ' : " DEMONLG ' , ' 123131 ' : , ' 32313 ' : " 2222 ' , ' 4343 ' : "} del a[ ' 1233 ' ] print (a) File "e:/python/day1/set.py", line, in <module> Del a[' 1233 '] Keyerror: ' 1233 '
Process finished with exit code 1 |
Pop
|
Delete the specified element |
A = {' name ': ' DEMONLG ', ' 123131 ': ' 2222 ', ' 32313 ': ' 2222 ', ' 4343 ': ' 24 '} A.pop (' 123131 ') Print (a)
{' name ': ' DEMONLG ', ' 32313 ': ' 2222 ', ' 4343 ': ' 24 '}
Process finished with exit code 0 |
Update
|
You can update the primary key and elements in another dictionary into an existing dictionary, or you can update a single element if you have the same primary key and element that overrides the previous primary key and element |
a = { ' name ' : " DEMONLG ' } B = { ' 2222 ' : ' 32313 ' } A.update (b) print (a) {' name ': ' DEMONLG ', ' 2222 ': ' 32313 '} |
clear |
empty list All contents |
a = { ' name ' : " DEMONLG ' } B = { ' 2222 ' : ' 32313 ' } A.clear () print (a) get: {} |
setdefault |
Returns the value corresponding to the specified key, adds a new element without a corresponding value, and sets the value of the key |
a = { ' name ' : " DEMONLG ' } A.setdefault ( ' 2222 ' , ' 32313 ' ) print (a) get {' name ': ' DEMONLG ', ' 2222 ': ' 32313 '} |
Dict.fromkeys |
Create a dictionary with x, Y, z as key and null value |
dict. Fromkeys ([' name ',' age '"man ') Print (A,C) {' name ': None, ' Ageman ': none}
|
This article is from the "Learning Notes" blog, so be sure to keep this source http://demonlg.blog.51cto.com/7229680/1976357
Day7 Dictionary of Python Learning