get() can "get the value" based on the key.
grammatical
( key, value )
parameters
- key : (Required) Specify the key to be searched.
- value : (optional) if the key does not exist, return the specified content
return value
- If the key exists, return the value corresponding to the key
- If the key does not exist, return the specified content or None
Example: Getting a dictionary value based on a key
dict1 = {'key1': 'value1', 'key2': 'value2'} print(('key1'))
Output:
value1
1、Set the default return value
get() can specify a "default" "return value". When the key does not exist, it will not report an error, but return a default value, which has the advantage that the program will not have an exception at runtime.
"If the key does not exist, the default return value is None.
dict1 = {'key1': 'value1', 'key2': 'value2'} print(('key3')) print(('key3', None))
Output:
None
None
"If the key does not exist, the return value will be specified.
dict1 = {'key1': 'value1', 'key2': 'value2'} print(('key3', 'Specify return value'))
Output:
Specify the return value
The return value can be of various data types such as integer, string, tuple, list, etc.
dict1 = {'key1': 'value1', 'key2': 'value2'} print(('key3', 1)) print(('key3', 1.1)) print(('key3', True)) print(('key3', [1, 2])) print(('key3', (1, 2))) print(('key3', {1, 2}))
Output:
1
1.1
True
[1, 2]
(1, 2)
{1, 2}
2、嵌套字典取值
dictionary「nested」dictionary time,Can be called multiple times get() ,take a value。
dict1 = {'key1': 'value1', 'key2': {'key3': 'value3'}} print(('key2').get('key3')) # Equivalent to this result = ('key2') print(result) result1 = ('key3') print(result1)
Output:
value3
{'key3': 'value3'}
value3
3, get() and dict[key] difference
Both get() and dict[key] can get the value of a dictionary based on the key, the difference being that the
If the key of get() does not exist in the dictionary, it returns "None" or "specified content".
dict1 = {'key1': 'value1', 'key2': 'value2'} print(('key3')) print(('key3', 'Specified content'))
Output:
None
Specify the content
If the key of dict[key] does not exist in the dictionary, it will "report an error" KeyError: 'key3'
dict1 = {'key1': 'value1', 'key2': 'value2'} print(dict1['key3'])
Output:
4. Statistical element counting
get() counts the number of occurrences of a list element and saves the result to a dictionary.
dict1 = {} list1 = ['¥', '¥', '¥', '$', '$', '$', '$', '$'] for i in list1: dict1[i] = (i, 0) + 1 print(dict1)
Output:
{'¥': 3, '$': 5}
to this article on the Python dictionary get () function to use the article is introduced to this, more related Python get () function content, please search for my previous posts or continue to browse the following related articles I hope you will support me in the future more!