This article mainly introduces the detailed operation method of Python dictionary (Dictionary). Friends who need it can refer to the following:
Python dictionaries are another mutable container model and can store objects of any type, such as strings, numbers, tuples, and other container models.
1. Create a dictionary A
dictionary consists of pairs of keys and corresponding values. Dictionaries are also known as associative arrays or hash tables. The basic syntax is as follows:
dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}
You can also create a dictionary like this
dict1 = { 'abc': 456 }; dict2 = { 'abc': 123, 98.6: 37 };
Note:
Each key and value are separated by a colon (:), each pair is separated by a comma, and each pair is separated by a comma, and the whole is enclosed in curly braces ({}).
Keys must be unique, but values do not.
Values can take any data type, but must be immutable, such as strings, numbers or tuples.
2. To access the value in the dictionary
Put the corresponding key into the familiar square brackets, as in the following example:
#!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}; print " dict['Name']: " , dict[ ' Name ' ]; print " dict['Age']: " , dict[ ' Age ' ]; #The output of the above example: # dict['Name']: Zara # dict['Age']: 7
If you access the data with a key that is not in the dictionary, you will get the following error:
#!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}; print "dict['Alice']: ", dict['Alice'];
The output of the above example is:
#dict['Zara']: #Traceback (most recent call last): # File "test.py", line 4, in <module> # print "dict['Alice']: ", dict['Alice']; #KeyError: 'Alice'[/code]
3. Modify
the dictionary The method of adding new content to the dictionary is to add new key/value pairs, and modify or delete existing key/value pairs as follows:
#!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}; dict['Age'] = 8; # update existing entry dict['School'] = "DPS School"; # Add new entry print " dict['Age']: " , dict[ ' Age ' ]; print " dict['School']: " , dict[ ' School ' ]; #The output of the above example: # dict['Age']: 8 # dict['School']: DPS School
Fourth, delete dictionary elements
can delete a single element can also clear the dictionary, clearing only one operation.
Display delete a dictionary with the del command, the following example:
#!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}; del dict[ ' Name ' ]; #delete the entry whose key is 'Name' dict.clear(); #clear all entries in the dictionary del dict ; #delete the dictionary print " dict['Age']: " , dict[ ' Age ' ]; print " dict['School']: " , dict[ ' School ' ]; # but this will raise an exception because the dictionary doesn't work after del Exists again: dict[ ' Age ' ]: # Traceback (most recent call last): # File "test.py", line 8, in <module> # print "dict['Age']: ", dict['Age ']; # TypeError: 'type' object is unsubscriptable
5. Characteristics of dictionary keys The
dictionary value can take any python object without limitation, it can be either a standard object or a user-defined one, but the key is not.
Two important points to remember:
1) Do not allow the same key to appear twice. If the same key is assigned twice during creation, the latter value will be remembered, as in the following example:
#!/usr/bin/python dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}; print " dict['Name']: " , dict[ ' Name ' ]; #The output of the above example: # dict['Name']: Manni
2) The key must be immutable, so it can be used as a number, string or tuple, so a list cannot be used, as in the following example:
#!/usr/bin/python dict = {['Name']: 'Zara', 'Age': 7}; print "dict['Name']: ", dict['Name']; #以上实例输出结果: #Traceback (most recent call last): # File "test.py", line 3, in <module> # dict = {['Name']: 'Zara', 'Age': 7}; #TypeError: list objects are unhashable
Six, dictionary built-in functions & methods
Python dictionary contains the following built-in functions:
1. cmp(dict1, dict2): Compare two dictionary elements.
2. len(dict): Calculate the number of dictionary elements, that is, the total number of keys.
3. str(dict): printable string representation of the output dictionary.
4. type(variable): Returns the input variable type. If the variable is a dictionary, it returns the dictionary type.
The Python dictionary contains the following built-in methods:
1. radiansdict.clear(): deletes all elements
in the dictionary 2. radiansdict.copy(): returns a shallow copy of a dictionary
3. radiansdict.fromkeys(): creates a new dictionary with the sequence The elements in seq are the keys of the dictionary, and val is the initial value corresponding to all 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, it returns the default value
5. radiansdict.has_key( key): Returns true if the key is in the dictionary dict, otherwise returns false
6. radiansdict.items(): returns a traversable (key, value) tuple array
as a list 7. radiansdict.keys(): returns a dictionary as a list All keys
8, radiansdict.setdefault(key, default=None): similar to get(), but if the key does not already exist in the dictionary, it will add the key and set the value to default
9, radiansdict.update(dict2) : Update the key/value pairs of the dictionary dict2 into dict
10. radiansdict.values(): Return all the values in the dictionary as a list