What is the usage of the Python dictionary get function…
The get() method of a dictionary is used to retrieve the value of a specified key in the dictionary. It takes two parameters: the first parameter is the key to retrieve, and the second parameter is an optional default value to return if the specified key does not exist in the dictionary.
Grammar:
字典.get(键, 默认值)
Original: 我学了英语,所以现在我可以跟外国人交流。
Paraphrased: I have studied English, so now I can communicate with foreigners.
person = {'name': 'Alice', 'age': 25, 'city': 'New York'}
name = person.get('name')
print(name) # 输出:Alice
gender = person.get('gender', 'unknown')
print(gender) # 输出:unknown
age = person.get('age', 30)
print(age) # 输出:25
salary = person.get('salary')
print(salary) # 输出:None
In the above example, the get() method is used to retrieve the value of a specified key in a dictionary, and a default value can be specified. If the specified key exists, it will return the corresponding value; if the specified key does not exist, it will return the default value. If no default value is specified, it will return None.