How can Python access a specific value in a dictionary?
To access a specific value in a dictionary, you can use either the dictionary’s index operation or the dictionary’s get() method.
By using dictionary indexing, you can retrieve the corresponding value by specifying the key. For example:
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
print(my_dict["name"]) # 输出:"Alice"
print(my_dict["age"]) # 输出:25
By using the get() method with a dictionary, you can retrieve the value corresponding to a specified key. Unlike indexing, if the key is not present in the dictionary, the get() method will return None or a specified default value instead of raising a KeyError. For instance:
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
print(my_dict.get("name")) # 输出:"Alice"
print(my_dict.get("age")) # 输出:25
print(my_dict.get("gender")) # 输出:None
print(my_dict.get("gender", "Unknown")) # 输出:"Unknown"
When using indexing in dictionaries, if the specified key does not exist, a KeyError exception will be raised. However, when using the get() method, if the specified key does not exist in the dictionary, it will return None or a specified default value. Therefore, if you are unsure whether a key exists in the dictionary, using the get() method is a safer option.