author : Han Xinzi @ShowMeAI
Tutorial address :http://www.showmeai.tech/tutorials/56
This paper addresses :http://www.showmeai.tech/article-detail/79
Statement : copyright , For reprint, please contact the platform and the author and indicate the source
Dictionary is another variable container model , And can store any type of object .
Each key value of the dictionary key=>value Yes, with a colon : Division , Comma between each key value pair , Division , The whole dictionary is enclosed in curly brackets {} in , The format is as follows :
d = {key1 : value1, key2 : value2 }
Keys are usually the only , If you repeat the last key value pair, the previous one will be replaced , Value doesn't need to be unique .
>>> dict = {'a': 1, 'b': 2, 'b': '3'} >>> dict['b'] '3' >>> dict {'a': 1, 'b': '3'} # dict = {'name': 'runoob', 'likes': 123, 'url': 'www.runoob.com'} dict = {'name': 'ShowMeAI', 'likes': 1000000, 'url': 'www.showmeai.tech'}
The value can take any data type , but The key must be immutable , Such as a string , A number or tuple .
A simple dictionary example :
dict1 = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'} dict2 = { 'abc': 123, 98.6: 37, (1,2):345 }
Put the corresponding key in the familiar square brackets , Here's a code example ( The code can be in On-line python3 Environmental Science Run in ):
dict = {'Name': 'ShowMeAI', 'Color': 'Blue', 'Class': 'First'} print("dict['Name']: ", dict['Name']) print("dict['Color']: ", dict['Color'])
The execution result of the above example :
dict['Name']: ShowMeAI dict['Color']: Blue
If you access data with keys that are not in the dictionary , The output error is as follows :
dict = {'Name': 'ShowMeAI', 'Color': 'Blue', 'Class': 'First'} print("dict['Age']: ", dict['Age'])
The output of the above example :
Traceback (most recent call last): File "<string>", line 5, in <module> KeyError: 'Age'
The way to add new content to the dictionary is to add new keys / It's worth it , Modify or delete existing keys / The value is shown in the following code example ( The code can be in On-line python3 Environmental Science Run in ):
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} dict['Age'] = 8 # to update dict['School'] = "ShowMeAI" # add to print "dict['Age']: ", dict['Age'] print "dict['School']: ", dict['School']
The output of the above example :
dict['Age']: 8 dict['School']: ShowMeAI
Can delete a single element can also empty the dictionary , Emptying takes only one operation .
Show delete a dictionary with del command , The following example :
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} del dict['Name'] # Delete key is 'Name' The entry of dict.clear() # Empty all dictionary entries del dict # Delete Dictionary print("dict['Age']: ", dict['Age'] ) print("dict['School']: ", dict['School'])
But this raises an exception , Because with del The post dictionary no longer exists :
Traceback (most recent call last): File "<string>", line 9, in <module> TypeError: 'type' object is not subscriptable
notes :del() Methods will also be discussed later .
The dictionary value can take any python object , It can be a standard object , It can also be user-defined , But the key doesn't work .
Two important points to remember :
1) The same key is not allowed to appear twice . When creating, if the same key is assigned twice , The latter value updates the previous one , The following example :
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'ShowMeAI'} print "dict['Name']: ", dict['Name']
The output of the above example :
dict['Name']: ShowMeAI
2) The key must be immutable , So you can use numbers , A string or tuple acts as , So using lists doesn't work , The following example :
dict = {['Name']: 'Zara', 'Age': 7} print("dict['Name']: ", dict['Name'])
The output of the above example :
Traceback (most recent call last): File "<string>", line 3, in <module> TypeError: unhashable type: 'list'
Python The dictionary contains the following built-in functions :
Functions and descriptions
effect
cmp(dict1, dict2)
Compare two dictionary elements .
len(dict)
Count the number of dictionary elements , That's the total number of bonds .
str(dict)
The printable string representation of the output Dictionary .
type(variable)
Returns the type of variable entered , If the variable is a dictionary, return the dictionary type .
Python The dictionary contains the following built-in methods :
Functions and descriptions
effect
dict.clear()
Delete all elements in the dictionary
dict.copy()
Returns a shallow copy of a dictionary
dict.fromkeys(seq[, val])
Create a new dictionary , In sequence seq The middle element is the key of the dictionary ,val Is the initial value of all keys in the dictionary
dict.get(key, default=None)
Returns the value of the specified key , If the value is not returned in the dictionary default value
dict.has_key(key)
If the key is in the dictionary dict Back in true, Otherwise return to false
dict.items()
Return traversable ( key , value ) View object of tuple array
dict.keys()
Returns a view object of all keys in the dictionary
dict.setdefault(key, default=None)
and get() similar , But if the key does not exist in the dictionary , The key will be added and the value will be set to default
dict.update(dict2)
Put the dictionary dict2 Key / Value pair update to dict in
dict.values()
Returns the view object of all values in the dictionary
pop(key[,default])
Delete dictionary given key key The corresponding value , The return value is the deleted value .key Value must be given . otherwise , return default value .
popitem()
Returns and deletes the last pair of keys and values in the dictionary .
Please click to B I'm looking at it from the website 【 Bilingual subtitles 】 edition
https://www.bilibili.com/video/BV1yg411c7Nw
The code for this tutorial series can be found in ShowMeAI Corresponding github Download , Can be local python Environment is running , Babies who can visit foreign websites can also directly use google colab One click operation and interactive operation learning Oh !
This tutorial series covers Python The quick look-up table can be downloaded and obtained at the following address :