Access Dictionary Elements in Python

  • Post category:Dictionary

Once you have created a dictionary in Python, you can easily access its elements using their respective keys. Let’s explore different methods to access dictionary elements.

Method 1: Using Square Brackets

# Method 1: Using Square Brackets
my_dict = {"name": "John", "age": 30, "city": "New York"}
print(my_dict["name"])

Output:

John

Method 2: Using the get() Method

# Method 2: Using the get() Method
my_dict = {"name": "John", "age": 30, "city": "New York"}
print(my_dict.get("age"))

Output:

30