A dictionary in Python is a data structure that stores data in key–value pairs.
It is unordered, mutable, and does not allow duplicate keys.
Think of it like a real dictionary:
You look up a word (key)
You get its meaning (value)
✅ Syntax
my_dict = {
"key1": "value1",
"key2": "value2",
}
π Basic Example
student = {
"name": "Raghav",
"age": 20,
"course": "Computer Science"
}
print(student)
Output:
{'name': 'Raghav', 'age': 20, 'course': 'Computer Science'}
π Accessing Values
print(student["name"])
print(student["age"])
π Adding a New Key–Value Pair
student["grade"] = "A"
print(student)
π Updating a Value
student["age"] = 21
π Deleting an Item
del student["course"]
OR
student.pop("course")
π Looping Through Dictionary
for key, value in student.items():
print(key, ":", value)
π Dictionary Inside Dictionary (Nested Dictionary)
college = {
"student1": {"name": "Raghav", "age": 20},
"student2": {"name": "Aman", "age": 22}
}
print(college["student1"]["name"])
No comments:
Post a Comment