How to Access Value by Key in Dictionary in Python
In Python, you access a value in a dictionary by using its
key inside square brackets like dict[key]. Alternatively, you can use the dict.get(key) method which returns None if the key is missing instead of an error.Syntax
To get a value from a dictionary, use the key inside square brackets or the get() method.
- dict[key]: Returns the value for the given key. Raises
KeyErrorif the key is not found. - dict.get(key): Returns the value for the key if it exists, otherwise returns
Noneor a default value if provided.
python
value = my_dict[key] value = my_dict.get(key) value = my_dict.get(key, default_value)
Example
This example shows how to access values by keys using both square brackets and the get() method.
python
my_dict = {'apple': 5, 'banana': 3, 'orange': 7}
# Access using square brackets
apple_count = my_dict['apple']
print('Apple count:', apple_count)
# Access using get() method
banana_count = my_dict.get('banana')
print('Banana count:', banana_count)
# Using get() with a default value for a missing key
grape_count = my_dict.get('grape', 0)
print('Grape count:', grape_count)Output
Apple count: 5
Banana count: 3
Grape count: 0
Common Pitfalls
Trying to access a key that does not exist using square brackets causes a KeyError. To avoid this, use the get() method which safely returns None or a default value instead.
python
# Wrong way - causes KeyError if key missing my_dict = {'a': 1} # print(my_dict['b']) # This will raise KeyError # Right way - safe access print(my_dict.get('b')) # Prints None print(my_dict.get('b', 0)) # Prints 0 as default
Output
None
0
Quick Reference
| Method | Description | Behavior if Key Missing |
|---|---|---|
| dict[key] | Access value by key | Raises KeyError |
| dict.get(key) | Access value by key safely | Returns None |
| dict.get(key, default) | Access value with default | Returns default value |
Key Takeaways
Use square brackets
dict[key] to access values but be careful of missing keys causing errors.Use
dict.get(key) to safely access values without errors if the key is missing.You can provide a default value to
get() to return instead of None when the key is missing.Always handle missing keys to avoid runtime errors in your programs.