Category: python
Python dictionary methods
Published on 02 Mar 2026
Explanation
Below will create a Python dictionary named
'student' with three key-value pairs:
name, age, and course.
Code:
student = {
'name': 'Praveen',
'age': 25,
'course': 'MERN'
}
Explanation
This accesses the value of the key 'name'
from the dictionary and prints it.
It will raise a KeyError if the key does not
exist.
Code:
print(student['name'])
Explanation
The get() method returns the value of the
specified key.
If the key is not found,
it returns None instead of raising an error.
Code:
print(student.get('age'))
Explanation
This adds a new key 'city' to the
dictionary or updates
it if it already exists.
Code:
student['city'] = 'Chennai'
Explanation
This loop iterates through
all key-value pairs in the dictionary
using the items() method.
Code:
for key, value in student.items(): print(key, value)