dict[key]
and dict.get(key)
are two ways to access dictionary values in Python. The difference is that dict.get(key)
takes two arguments while dict[key]
takes one argument only.
In dict[key]
, if the key is missing in the dictionary then a KeyError
is raised.
The second argument of dict.get(key)
is the default value and is returned when the key is missing there in the dictionary. If the default is not given, it defaults to None, so that this method never raises a KeyError
.
Example: dict[key] vs dict.get(key)
Code:
my_dict = {
'key1':'value1',
'key2':'value2',
'key3':'value3',
'key4':'value4'
}
print(my_dict)
print(my_dict.get('key1'))
print(my_dict['key1'])
print(my_dict.get('key5', 'some value'))
print(my_dict['key5'])
Output:
{'key1': 'value1', 'key2': 'value2', 'key3': 'value3', 'key4': 'value4'} value1 value1 some value Traceback (most recent call last): File "main.py", line 16, in <module> print(my_dict['key5']) KeyError: 'key5'
Note: This default value of .get()
method is returned only if the key is not present in the dictionary, if the key is there in the dictionary, then whatever the value is will be returned.
Implementing dict.get(key) with dict[key]
Code:
my_dict = {
'key1':'value1',
'key2':'value2',
'key3':'value3',
'key4':'value4'
}
try:
value5 = my_dict["key5"]
except KeyError:
value5 = "value5"
print(value5)
Output:
value5
Accessing dictionary keys using loop
Code:
my_dict = {
'key1':'value1',
'key2':'value2',
'key3':'value3',
'key4':'value4'
}
for key in my_dict:
print(key)
Output:
key1 key2 key3 key4
Access dictionary values in Python using loop
Code:
my_dict = {
'key1':'value1',
'key2':'value2',
'key3':'value3',
'key4':'value4'
}
for key in my_dict:
print(my_dict[key])
Output:
value1 value2 value3 value4
Click here to check the discussion on dict[key] vs dict.get(key) on StackOverflow.
Thank you for visiting our website.
Also Read:
- Create your own ChatGPT with Python
- SQLite | CRUD Operations in Python
- Event Management System Project in Python
- Ticket Booking and Management in Python
- Hostel Management System Project in Python
- Sales Management System Project in Python
- Bank Management System Project in C++
- Python Download File from URL | 4 Methods
- Python Programming Examples | Fundamental Programs in Python
- Spell Checker in Python
- Portfolio Management System in Python
- Stickman Game in Python
- Contact Book project in Python
- Loan Management System Project in Python
- Cab Booking System in Python
- Brick Breaker Game in Python
- Tank game in Python
- GUI Piano in Python
- Ludo Game in Python
- Rock Paper Scissors Game in Python
- Snake and Ladder Game in Python
- Puzzle Game in Python
- Medical Store Management System Project in Python
- Creating Dino Game in Python
- Tic Tac Toe Game in Python
- Test Typing Speed using Python App
- Scientific Calculator in Python
- GUI To-Do List App in Python Tkinter
- Scientific Calculator in Python using Tkinter
- GUI Chat Application in Python Tkinter