Extract Values from Python Dictionary
There are two ways to access values from a Python dictionary, which is by using square brackets [] or the get() method.
For example:
my_dict = {'name': 'Alice', 'age': 30}
# 使用方括号 [] 获取值
name = my_dict['name']
age = my_dict['age']
print(name) # 输出:Alice
print(age) # 输出:30
# 使用 get() 方法获取值
name = my_dict.get('name')
age = my_dict.get('age')
print(name) # 输出:Alice
print(age) # 输出:30
When retrieving a value using square brackets [], a KeyError exception is thrown if the key does not exist; whereas when retrieving a value using the get() method, it will return None if the key does not exist, and you can also set a default value, for example:
# 使用 get() 方法获取值,并设置默认值
country = my_dict.get('country', 'Unknown')
print(country) # 输出:Unknown