Python3 dictionary Dict (13), python3 dictionary dict
Python has built-in dictionaries: dict support. dict stands for dictionary and is also called map in other languages. It is stored with key-value (key-value) and has extremely fast search speed.
Dictionary is another variable container model that can store any type of objects.
Each key-value (key => value) pair of the dictionary uses the colon (:), And each pair is separated by a comma (,The entire dictionary is included in curly brackets ({})The format is as follows:
d = {key1 : value1, key2 : value2 }
The key must be unique, but the value is not required..
Values can be of any data type, but keys must be unchangeable, such as strings, numbers, or tuples.
A simple dictionary example:
1 dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
You can also create a dictionary as follows:
1 dict1 = { 'abc': 456 };2 dict2 = { 'abc': 123, 98.6: 37 };
Value in the access dictionary
Place the corresponding keys in the familiar square brackets, as shown in the following example:
1 #!/usr/bin/python32 3 dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}4 5 print ("dict['Name']: ", dict['Name'])6 print ("dict['Age']: ", dict['Age'])
Output result of the above instance:
1 dict['Name']: Runoob2 dict['Age']: 7
If you use a key that is not in the dictionary to access data, an error is returned.
1 >>> info = {'stu1102': 'longze Luola ', 'stu1103 ': 'xiaoze Maliya '} 2 >>> 3 >>> "stu1102" in info # standard usage 4 True 5 >>> info. get ("stu1102") # obtain 6 'longze Luola '7> info ["stu1102"] # Same as above, but let's see the following 8 'longze Luola '9 >>> info ["stu1105"] # If a key does not exist, an error is returned. get does not, if not, only None10 Traceback (most recent call last): 11 File "<stdin>", line 1, in <module> 12 KeyError: 'stu1105' is returned'
Modify dictionary
You can add a new key/value pair to a dictionary to modify or delete an existing key/value pair as follows:
1 #! /Usr/bin/python3 2 3 dict = {'name': 'runoob', 'age': 7, 'class ': 'first'} 4 5 dict ['age'] = 8; # update Age 6 dict ['school '] = "cainiao tutorial" # add information 7 8 9 print ("dict ['age']:", dict ['age']) 10 print ("dict ['school ']:", dict ['school'])
Output result of the above instance:
1 dict ['age']: 82 dict ['school ']: cainiao tutorial
Delete dictionary elements
Only one operation is required to delete a single element and clear the dictionary.
The following example shows how to delete a dictionary using the del command:
1 #! /Usr/bin/python3 2 3 dict = {'name': 'runoob', 'age': 7, 'class ': 'first'} 4 5 del dict ['name'] # Delete the 'name' 6 dict. clear () # Delete dictionary 7 del dict # Delete dictionary 8 9 print ("dict ['age']:", dict ['age']) 10 print ("dict ['school ']:", dict ['school'])
However, this causes an exception because the dictionary does not exist after del is executed:
1 Traceback (most recent call last):2 File "test.py", line 9, in <module>3 print ("dict['Age']: ", dict['Age'])4 TypeError: 'type' object is not subscriptable
1 >>> info 2 {'stu1102': 'longze Luola ', 'stu1103': 'xiaoze Maliya', 'stu1101': 'lan'} 3 >>> info. pop ("stu1101") # standard Delete posture 4 'ran' 5> info 6 {'stu1102': 'longze Luola ', 'stu1103 ': 'xiaoze Maliya '} 7 >>> del info ['stu1103'] # change the posture to delete 8 >>> info 9 {'stu1102 ': 'longze Luola '} 10 >>> 11 >>>> 12 >>>>13 >>> info = {'stu1102': 'longze Luola', 'stu1103 ': 'xiaoze Maliya '} 14 >>> info15 {'stu1102': 'longze Luola', 'stu1103': 'xiaoze Maliya '} # Delete randomly 16 >>> info. popitem () 17 ('stu1102', 'longze Luola ') 18 >>> info19 {'stu1103': 'xiaoze Maliya '}
Dictionary key features
The dictionary value can be any python object, either a standard object or a user-defined object, but the key cannot.
There are two important points to remember:
1) the same key cannot appear twice. If the same key is assigned twice during creation, the last value will be remembered as follows:
1 #! /Usr/bin/python32 3 dict = {'name': 'runoob', 'age': 7, 'name ': 'cainiao '} 4 5 print ("dict ['name']:", dict ['name'])
Output result of the above instance:
1 dict ['name']: cainiao
2) The key must be unchangeable. Therefore, you can use numbers, strings, or tuples, but not lists. For example:
1 #!/usr/bin/python32 3 dict = {['Name']: 'Runoob', 'Age': 7}4 5 print ("dict['Name']: ", dict['Name'])
Output result of the above instance:
1 Traceback (most recent call last):2 File "test.py", line 3, in <module>3 dict = {['Name']: 'Runoob', 'Age': 7}4 TypeError: unhashable type: 'list'
Circular dictionary method:
# Method 1for key in info: print (key, info [key]) # method 2for k, v in info. items (): # convert dict to list first. print (k, v) is not used when the data is large)
1 dic = {"name": "lhm", "age": 33, "address": "wuhan", "job": "coding"}2 for i in dic:3 print(i, dic[i])4 print("-------------------------------")5 for a, b in dic.items():6 print(a, b)
The result is as follows:
1 job coding2 name lhm3 address wuhan4 age 335 -------------------------------6 job coding7 name lhm8 address wuhan9 age 33
Dictionary built-in functions & Methods
The Python dictionary contains the following built-in functions:
The Python dictionary contains the following built-in methods:
Serial number |
Functions and descriptions |
1 |
Radiansdict. clear () Delete all elements in the dictionary |
2 |
Radiansdict. copy () Returns the shortest copy of a dictionary. |
3 |
Radiansdict. fromkeys () Create a new dictionary and use the elements in sequence seq as the dictionary key. val is the initial value corresponding to all the keys in the dictionary. |
4 |
Radiansdict. get (key, default = None) Returns the value of the specified key. If the value is not in the dictionary, the default value is returned. |
5 |
Key in dict If the key returns true in the dictionary dict, otherwise false is returned. |
6 |
Radiansdict. items () Returns a list of traversal (Key, value) tuples. |
7 |
Radiansdict. keys () Returns all keys of a dictionary in a list. |
8 |
Radiansdict. setdefault (key, default = None) Similar to get (), but if the key does not exist in the dictionary, a key is added and the value is set to default. |
9 |
Radiansdict. update (dict2) Update the dictionary dict2 key/value pairs to dict. |
10 |
Radiansdict. values () Returns all values in the dictionary as a list. |
11 |
Pop (key [, default]) Delete the value corresponding to the specified key in the dictionary. The returned value is the deleted Value. The key value must be given. Otherwise, the default value is returned. |
12 |
Popitem () Returns and deletes a pair of keys and values in the dictionary randomly (generally, the end pair is deleted ). |