What is the method for retrieving values from a Python dictionary index?
In Python, you can use square brackets [] or the get() method to access values in a dictionary.
- Square brackets []: Values can be accessed by specifying the key. If the key does not exist, a KeyError error will occur.
For example: - my_dict is a dictionary with three key-value pairs. The value associated with the key “key2” is accessed and printed, which is “value2”.
- The get() method allows you to retrieve the value corresponding to a specified key. If the key does not exist, you can set a default value to return instead, without causing a KeyError error. For example:
- my_dict = {“key1”: “value1”, “key2”: “value2”, “key3”: “value3”}
value = my_dict[“key2”]
print(value) # Output: value2value = my_dict.get(“key4”, “default”)
print(value) # Output: default
Both methods can be used to retrieve values from a dictionary, the choice of which method to use depends on whether or not you need to handle cases where the key does not exist.