There are many simple functional applications in the Python programming language, but they are very powerful in actual programming. For example, the application of the Python dictionary is one of the most important applications. Next, we will give a detailed introduction to the Python dictionary application method.
Python dictionary application method 1) get (key, default = None)
Returns the value corresponding to the key. If the key is not in the dictionary, the default value is returned. The default value is None.
- >>> Dict1 # empty dictionary
- {}
- >>> Dict1.get ('A') # key 'A' does not exist in dict1, and none is returned.
- >>> Dict1.get ('d1 ', 'no1') # The default parameter provides the value 'no1', so 'no1' is returned'
- 'No1'
- >>> Dict1 ['a'] = 'no1' # Insert a new element
- >>> Dict1
- {'A': '000000 '}
- >>> Dict1.get ('A') # The current key 'A' exists and its value is returned.
- '123'
2) clear
Clear dictionary
3) has_key (key)
If the key appears in dict, True is returned; otherwise, False is returned.
- >>> dict1
- {'a': '1111'}
- >>> dict1.has_key('b')
- False
- >>> dict1.has_key('a')
- True
4) items
The main function of this Python dictionary application is to return the dict key and value) a list of tuple pairs.
- >>> dict1
- {'a': 'no1', 'b': '2222'}
- >>> dict1.items()
- [('a', 'no1'), ('b', '2222')]
5) keys returns the dict Key List
6) values returns the dict Value List
- >>> dict1
- {'a': 'no1', 'b': '2222'}
- >>> dict1.keys()
- ['a', 'b']
- >>> dict1.values()
- ['no1', '2222']
7) setdefault (key, default = None)
If a key exists in dict, the key value is returned. If no key is found, the key is added to dict. The value is given by the default parameter. The default value is None.
8) update (dict2)
Add the dict2 element to dict. When the key word is repeated, it overwrites the key value in dict.
- >>> Dict2
- {'C': '000000', 'B': 'no2 '}
- >>> Dict1 # The keys 'B' of dict2 and dict1 are repeated.
- {'A': 'no1', 'B': '000000 '}
- >>> Dict1.update (dict2) # After update is called, the 'B' VALUE OF THE dict1 key is overwritten.
- >>> Dict1
- {'A': 'no1', 'C': '000000', 'B': 'no2 '}
9) popitem
This Python dictionary application deletes any key-Value Pair and returns the key-value pair. If the dictionary is empty, an exception occurs.
- >>> dict1
- {'b': 'no2'}
- >>> dict1.popitem()
- ('b', 'no2')
- >>> dict1
- {}
- >>> dict1.popitem()
- Traceback (most recent call last):
- File "< interactive input>", line 1, in < module>
- KeyError: 'popitem(): dictionary is empty'
10) pop (key, [d])
Delete the key-value pair of the specified key word and return the value corresponding to the key # The second parameter does not know how to use
- >>> dict1
- {'a': 'no1', 'c': '3333', 'b': 'no2'}
- >>> dict1.pop('a')
- 'no1'
- >>> dict1
- {'c': '3333', 'b': 'no2'}
11) copy
Returns a shortest copy of the dictionary.
The preceding section describes how to use the Python dictionary.