Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to print a value for a given key for Python dictionary?
Python dictionary is a collection of key-value pairs. There are several ways to print or access the value associated with a specific key.
Using the get() Method
The get() method returns the value for a given key. If the key doesn't exist, it returns None by default ?
D1 = {'a': 11, 'b': 22, 'c': 33}
print(D1.get('b'))
print(D1.get('d')) # Key doesn't exist
22 None
Using get() with Default Value
You can provide a default value to return when the key is not found ?
D1 = {'a': 11, 'b': 22, 'c': 33}
print(D1.get('d', 'Key not found'))
print(D1.get('b', 'Key not found'))
Key not found 22
Using Square Bracket Notation
You can access values directly using the key inside square brackets ?
D1 = {'a': 11, 'b': 22, 'c': 33}
print(D1['c'])
print(D1['a'])
33 11
Handling KeyError
Square bracket notation raises a KeyError if the key doesn't exist ?
D1 = {'a': 11, 'b': 22, 'c': 33}
try:
print(D1['d']) # This will raise KeyError
except KeyError:
print("Key 'd' not found in dictionary")
Key 'd' not found in dictionary
Comparison
| Method | Key Exists | Key Missing | Best For |
|---|---|---|---|
get() |
Returns value | Returns None | Safe access |
get(key, default) |
Returns value | Returns default | Custom fallback |
dict[key] |
Returns value | Raises KeyError | When key must exist |
Conclusion
Use get() method for safe dictionary access without errors. Use square bracket notation when you're certain the key exists or want to handle the KeyError explicitly.
Advertisements
