A Dictionary in Python (programming language) is used to store data in keyβvalue pairs.
Each item in a dictionary has:
- a key ποΈ
- a value π¦
Example:{"name": "Rahul", "age": 20}
Here:
nameβ keyRahulβ value
Key Features
- Ordered (from Python 3.7+)
- Mutable (can change values)
- Keys must be unique
- Values can be any data type
1οΈβ£ Creating a Dictionary
Dictionaries use curly braces {}.
student = {
"name": "Rahul",
"age": 20,
"course": "Python"
}
print(student)
Output
{'name': 'Rahul', 'age': 20, 'course': 'Python'}
2οΈβ£ Accessing Dictionary Values
Use the key to access values.
student = {
"name": "Rahul",
"age": 20
}
print(student["name"])
print(student["age"])
Output
Rahul
20
3οΈβ£ Using get() Method
get() is safer because it does not cause an error if the key doesn’t exist.
student = {"name": "Rahul", "age": 20}print(student.get("name"))
4οΈβ£ Changing Dictionary Values
Values can be modified easily.
student = {
"name": "Rahul",
"age": 20
}
student["age"] = 21
print(student)
Output
{'name': 'Rahul', 'age': 21}
5οΈβ£ Adding New Items
Add a new key-value pair.
student = {
"name": "Rahul",
"age": 20
}
student["city"] = "Delhi"
print(student)
Output
{'name': 'Rahul', 'age': 20, 'city': 'Delhi'}
6οΈβ£ Removing Items
pop()
Removes an item using a key.
student = {
"name": "Rahul",
"age": 20
}
student.pop("age")
print(student)
Output
{'name': 'Rahul'}
del
student = {
"name": "Rahul",
"age": 20
}
del student["age"]
print(student)
7οΈβ£ Dictionary Length
Use len() to count items.
student = {
"name": "Rahul",
"age": 20,
"city": "Delhi"
}
print(len(student))
Output
3
8οΈβ£ Loop Through a Dictionary
Loop through keys.
student = {
"name": "Rahul",
"age": 20
}
for key in student:
print(key)
Output
name
age
Loop through values.
for value in student.values():
print(value)
Loop through key-value pairs.
for key, value in student.items():
print(key, value)
9οΈβ£ Nested Dictionary
A dictionary can contain another dictionary.
students = {
"student1": {"name": "Rahul", "age": 20},
"student2": {"name": "Amit", "age": 21}
}
print(students["student1"]["name"])
Output
Rahul
π Clear a Dictionary
student = {"name": "Rahul", "age": 20}
student.clear()
print(student)
Output
{}
β Summary
| Feature | Dictionary |
|---|---|
| Structure | Key : Value |
| Ordered | Yes |
| Mutable | Yes |
| Duplicate Keys | Not Allowed |
β Example Program
student = {
"name": "Rahul",
"age": 20
}
student["course"] = "Python"for key, value in student.items():
print(key, ":", value)
Output
name : Rahul
age : 20
course : Python