Python Dictionary: Get Value by Key

You can retrieve the value of a specific key from a dictionary by using the following method:

# 创建一个字典
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}

# 使用键来获取值
name = my_dict['name']
print(name)  # 输出:Alice

age = my_dict['age']
print(age)  # 输出:30

Additionally, you can use the get() method to retrieve a value, which prevents a KeyError exception from occurring if the key does not exist.

name = my_dict.get('name')
print(name)  # 输出:Alice

gender = my_dict.get('gender', 'Unknown')
print(gender)  # 输出:Unknown

In the given example, if the key ‘gender’ is not in the dictionary, the get() method will return the default value ‘Unknown’.

bannerAds