How can you access dictionary values using their keys?

QuestionsQuestions8 SkillsProPython Data StructuresSep, 23 2025
0105

In Python, you can access dictionary values using their keys in several ways:

1. Using Square Brackets

The most common method is to use square brackets [] with the key inside:

my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
print(my_dict['name'])  # Outputs: Alice

2. Using the get() Method

You can also use the get() method, which is safer because it allows you to specify a default value if the key does not exist:

print(my_dict.get('age'))          # Outputs: 25
print(my_dict.get('country', 'N/A'))  # Outputs: N/A (default value)

3. Checking for Key Existence

Before accessing a value, you might want to check if the key exists using the in operator:

if 'city' in my_dict:
    print(my_dict['city'])  # Outputs: New York

Summary

  • Use my_dict[key] for direct access.
  • Use my_dict.get(key) for safer access with a default value.
  • Check for key existence with 'key' in my_dict.

These methods provide flexibility in accessing dictionary values based on your needs. If you have any further questions or need examples, feel free to ask!

0 Comments

no data
Be the first to share your comment!