Get() Method in PythonPython's get() function can be used to access the objects of a dictionary, meaning the keys and their corresponding values. You can use the get() method following the below syntax: dictionary.get(key, default) The parameters can be described as follows:
The get() method searches the entire dictionary for the provided key, and if it exists, its associated value in the dictionary is returned. The default value (or None if no default value is specified) is returned if the key cannot be found. An example code snippet:Output: 3 None 0 Explanation: In the above example, we have a dictionary of "cars" that contains the count of various cars. Using get(), we retrieve the default values of 0 for the keys "ferrari", "mercedes", and "alpine". If the corresponding key exists in the dictionary while using the get() method, its corresponding value is returned to the console. If not, a default value passed as an argument in the function call is returned to the console. If the key is not found in the dictionary, you can use the get() function to avoid "KeyError". It is a safe technique for obtaining values from dictionaries, especially when the key is unknown.
Output: Unknown_Area
Output: [1] [2] [] Explanation: In this example, the default value [] is a changeable list. The value for the key 'list' is appended to the list when we retrieve it. When we later obtain the value for the key 'count', it adds 2 to the same list. Consequently, retrieving the value for the key 'count' again includes both 2 and 1 because it is the same list that was previously modified.
Output: ERROR! None None None Traceback (most recent call last): File " Explanation: In this example, using square bracket indexing, providing None as a default value (result1 = data['key1']) returns the actual value None. When attempting to access a non-existent key (result2 = data['key3']), a KeyError is raised. On the other hand, providing None as the default value with get() method, returns the actual value None (result3 = data.get('key1', None)). Similarly, when attempting to retrieve a non-existent key (result4 = data.get('key3', None)), the default value None is returned.
Output: Unknown Unknown Explanation: In this example, we can clearly observe that there is no need for a conditional statement to check for the key "city" by using the get() method.
Next Topic"isna()" Function in Python
|