Python Notes – Class 12 CBSE
4. DICTIONARY IN PYTHON
A Dictionary is a collection of data stored in the form of key:value pairs. It is one of the most
useful data types in Python.
• Dictionary is mutable (can be changed).
• Dictionary stores data in key:value form.
• Keys must be unique.
• Values can be duplicated.
• Dictionary elements are enclosed in curly braces { }.
Creating a Dictionary
student = {
"name": "Riya",
"marks": 95,
"class": 12
}
print(student)
Output:
{'name': 'Riya', 'marks': 95, 'class': 12}
Accessing Dictionary Values
student = {
"name": "Riya",
"marks": 95
}
print(student["name"])
Output:
Riya
Updating Dictionary
student = {
"name": "Riya",
"marks": 95
}
student["marks"] = 98
print(student)
Output:
{'name': 'Riya', 'marks': 98}
Adding New Element in Dictionary
student = {
"name": "Riya"
}
student["age"] = 17
print(student)
Output:
{'name': 'Riya', 'age': 17}
Deleting Elements from Dictionary
student = {
"name": "Riya",
"marks": 95
}
del student["marks"]
print(student)
Output:
{'name': 'Riya'}
Common Dictionary Functions
Function Purpose
keys() Displays all keys
values() Displays all values
items() Displays key-value pairs
update() Updates dictionary
pop() Removes an item
clear() Removes all elements
Example Using Dictionary Functions
student = {
"name": "Riya",
"marks": 95
}
print([Link]())
print([Link]())
print([Link]())
Output:
dict_keys(['name', 'marks'])
dict_values(['Riya', 95])
dict_items([('name', 'Riya'), ('marks', 95)])
Advantages of Dictionary
• Fast data access using keys.
• Useful for storing structured data.
• Easy to update and modify.
Important Viva Questions
1. What is a dictionary in Python?
2. Why must keys be unique in a dictionary?
3. Difference between list and dictionary.
4. What is the use of items() function?