Author: Han Xinzi@ShowMeAI
Tutorial address: http://www.showmeai.tech/tuto...
Article address: http://www.showmeai.tech/article-detail/79
Notice: All Rights Reserved. Please contact the platform and the author for reprint and indicate the source
1.Python dictionary
A dictionary is another variable container model and can store objects of any type.
Each key = > value pair of the dictionary is separated by colon, and each key value pair is separated by comma. The whole dictionary is included in curly brackets {}, with the format as follows:
d = {key1 : value1, key2 : value2 }
The key is generally unique. If the last key value pair is repeated, the previous value will be replaced. The value does not 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 string, number or tuple.
A simple dictionary example:
dict1 = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'} dict2 = { 'abc': 123, 98.6: 37, (1,2):345 }
2. Access the values in the dictionary
Put the corresponding key into the familiar square brackets. Here is the code example (the code can be found in Online Python 3 environment Running in:
dict = {'Name': 'ShowMeAI', 'Color': 'Blue', 'Class': 'First'} print("dict['Name']: ", dict['Name']) print("dict['Color']: ", dict['Color'])
Execution results of the above examples:
dict['Name']: ShowMeAI dict['Color']: Blue
If you access data with keys that are not in the dictionary, an error will be output as follows:
dict = {'Name': 'ShowMeAI', 'Color': 'Blue', 'Class': 'First'} print("dict['Age']: ", dict['Age'])
Output results of the above examples:
Traceback (most recent call last): File "<string>", line 5, in <module> KeyError: 'Age'
3. Revise the dictionary
The way to add new content to the dictionary is to add new key / value pairs, modify or delete existing keys / values. The following code example (the code can be found in Online Python 3 environment Running 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']
Output results of the above examples:
dict['Age']: 8 dict['School']: ShowMeAI
4. Delete dictionary elements
You can delete a single element or empty the dictionary. Emptying requires only one operation.
The del command for deleting a dictionary is displayed, as shown in the following example:
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} del dict['Name'] # Delete entries whose key is' Name ' dict.clear() # Clear all entries in the dictionary del dict # Delete dictionary print("dict['Age']: ", dict['Age'] ) print("dict['School']: ", dict['School'])
But this raises an exception because the dictionary no longer exists after del:
Traceback (most recent call last): File "<string>", line 9, in <module> TypeError: 'type' object is not subscriptable
Note: the del() method will also be discussed later.
(1) Characteristics of dictionary keys
The dictionary value can take any python object without restriction, which can be either a standard object or a user-defined object, but the key does not work.
Two important points to remember:
1) The same key is not allowed to appear twice. If the same key is assigned twice during creation, the latter value will update the previous one, as shown in the following example:
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'ShowMeAI'} print "dict['Name']: ", dict['Name']
Output results of the above examples:
dict['Name']: ShowMeAI
2) Keys must be immutable, so you can use numbers, strings or tuples as keys, so you can't use lists. For example:
dict = {['Name']: 'Zara', 'Age': 7} print("dict['Name']: ", dict['Name'])
Output results of the above examples:
Traceback (most recent call last): File "<string>", line 3, in <module> TypeError: unhashable type: 'list'
5. Dictionary built-in functions and methods
The Python dictionary contains the following built-in functions:
Function and description | effect |
---|---|
cmp(dict1, dict2) | Compare two dictionary elements. |
len(dict) | Calculate the number of dictionary elements, that is, the total number of keys. |
str(dict) | Output dictionary printable string representation. |
type(variable) | Returns the type of the input variable. If the variable is a dictionary, it returns the dictionary type. |
The Python dictionary contains the following built-in methods:
Function and description | 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, use the element in seq sequence as the key of the dictionary, and val is the initial value corresponding to all keys of the dictionary |
dict.get(key, default=None) | Returns the value of the specified key. If the value is not in the dictionary, it returns the default value |
dict.has_key(key) | If the key returns true in dictionary dict, otherwise it returns false |
dict.items() | Returns the view object of a traversable (key, value) tuple array |
dict.keys() | Returns the view object of all keys in a dictionary |
dict.setdefault(key, default=None) | Similar to get(), but if the key does not exist in the dictionary, the key is added and the value is set to default |
dict.update(dict2) | Update the key / value pair of dictionary dict2 to dict |
dict.values() | Returns the view object of all values in the dictionary |
pop(key[,default]) | Delete the value corresponding to the key given in the dictionary, and the return value is the deleted value. The key value must be given. Otherwise, the default value is returned. |
popitem() | Returns and deletes the last pair of keys and values in the dictionary. |
6. Video tutorial
Please click to station B to view the version of [bilingual subtitles]
https://www.bilibili.com/vide...
Data and code download
The code for this tutorial series can be found in github corresponding to ShowMeAI Download in, you can run in the local python environment. Babies who can surf the Internet scientifically can also directly use Google lab to run and learn through interactive operation!
The Python quick look-up table involved in this tutorial series can be downloaded and obtained at the following address:
Extended references
ShowMeAI related articles recommended
- Introduction to python
- python installation and environment configuration
- python basic syntax
- python basic data type
- python operator
- python conditional control and if statement
- python loop statement
- python while loop
- python for loop
- python break statement
- python continue statement
- python pass statement
- python string and operation
- python list
- python tuple
- python dictionary
- python collection
- python function
- python iterators and generators
- python data structure
- python module
- python file reading and writing
- python file and directory operation
- python error and exception handling
- python object oriented programming
- python namespace and scope
- python time and date
ShowMeAI series tutorial recommendations
- Illustrated Python Programming: a series of tutorials from getting started to mastering
- Graphic data analysis: a series of tutorials from introduction to mastery
- Fundamentals of graphic AI Mathematics: a series of tutorials from introduction to mastery
- Illustrated big data technology: a series of tutorials from introduction to mastery