Retrieving values from a dictionary based on specific keys allows you to access the corresponding values stored in the dictionary. In this blog post, we will explore different methods to retrieve values from a dictionary using keys in Python.
Method 1: Using the square bracket notation
# Method 1: Using the square bracket notation my_dict = {"name": "John", "age": 30, "city": "New York"} name = my_dict["name"] print("Name:", name)
Output:
Name: John
Method 2: Using the get() method
# Method 2: Using the get() method my_dict = {"name": "John", "age": 30, "city": "New York"} age = my_dict.get("age") print("Age:", age)
Output:
Age: 30