Get() Method in Python
Python'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:
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:
3 None 0
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.
  
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.
ERROR! None None None Traceback (most recent call last): File "
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.
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.
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week