What is the usage of the “get” method in Python dictionaries?
In Python, get() is a method used to access elements in a dictionary. It takes a key as a parameter and returns the corresponding value. The get() method has two parameters: the key and a default value. If the given key exists in the dictionary, it will return the associated value; if the key does not exist, it will return the default value.
The grammar is as follows:
dictionary.get(key, default_value)
In which, key is the key to be accessed, and default_value is an optional default value. If no default value is provided, it defaults to None.
Example of usage:
person = {'name': 'John', 'age': 30, 'city': 'New York'}
name = person.get('name')
print(name) # 输出:John
country = person.get('country', 'Unknown')
print(country) # 输出:Unknown,因为字典中不存在'country'键
city = person.get('city', 'Unknown')
print(city) # 输出:New York,因为字典中存在'city'键
The difference between using the get() method and directly using the index operator [] to access dictionary elements is that when the key does not exist, using the index operator will raise a KeyError exception, while the get() method will return a default value. This makes the get() method safer for handling non-existent keys.