In Python, get() is a built-in method that is used to access the value of a key in a dictionary. It returns the value associated with the given key, and if the key is not present in the dictionary, it returns a default value. The get() method takes one or two arguments: the key to look up and an optional default value to return if the key is not found.
The syntax of the get() method is as follows:
| dictionary.get(key[, default]) |
key: This is the key to look up in the dictionary.default: This is an optional argument that specifies the value to return if the key is not found. If this argument is not specified, None is returned by default.Here's an example of using the get() method to retrieve the value associated with a key in a dictionary:
|
# Define a dictionary
person = {'name': 'Alice', 'age': 30, 'city': 'New York'}
# Get the value associated with the key 'name'
name = person.get('name')
# Print the value of name
print(name) # Output: 'Alice'
# Get the value associated with the key 'gender' (which doesn't exist)
gender = person.get('gender')
# Print the value of gender
print(gender) # Output: None
# Get the value associated with the key 'gender' and provide a default value of 'unknown'
gender = person.get('gender', 'unknown')
# Print the value of gender
print(gender) # Output: 'unknown'
|
In the first example, the get() method is used to retrieve the value associated with the key 'name'. Since the key exists in the dictionary, the method returns the value 'Alice'.
In the second example, the get() method is used to retrieve the value associated with the key 'gender', which does not exist in the dictionary. Since no default value is provided, the method returns None.
In the third example, the get() method is used to retrieve the value associated with the key 'gender'. Since the key does not exist in the dictionary, the default value 'unknown' is returned instead of None.