Dictionary Intro
What is a Dictionary?
A dictionary in Python is a collection of key-value pairs.
Unlike lists, dictionaries allow fast lookups using keys
instead of indices.
📌 Creating a Dictionary: Using {} or dict()
📌 Accessing Elements: Using keys
📌 Adding & Updating Items: Assigning values to keys
📌 Removing Items: Using del, pop(), clear()
Creating a Dictionary
Dictionaries are created using curly braces {} or the dict() function.
Example: Creating a Dictionary
student = {
"name": "Ajay",
"age": 25,
"course": "Python"
}
print(student)
Output:
{'name': 'Ajay', 'age': 25, 'course': 'Python'
Accessing Elements in a Dictionary
You can access values using keys.
Example: Accessing Specific Values
student = {
"name": "Ajay",
"age": 25,
"course": "Python"
}
print(student["name"]) # Access 'name'
print([Link]("age")) # Access 'age' using
Output:
Ajay
25
Adding & Updating Items
You can add new key-value pairs or update existing ones.
Example: Adding & Updating Values
student = {
"name": "Ajay",
"age": 25,
"course": "Python"
}
student["grade"] = "A" # Adding a new key-val
student["age"] = 26 # Updating an existing va
print(student)
Output:
{'name': 'Ajay', 'age': 26, 'course': 'Python'
Removing Items
You can remove items using del, pop(), or clear().
Example: Removing Elements
student = {
"name": "Ajay",
"age": 25,
"course": "Python",
"grade": "A"
}
del student["grade"] # Remove 'grade'
removed_value = [Link]("age") # Remove '
print(student)
print(f"Removed Value: {removed_value}")
Output:
{'name': 'Ajay', 'course': 'Python'}
Removed Value: 25
When to Use Dictionaries?
✅ Fast Lookups: When you need quick access to values using
keys.
✅ Structured Data: When storing related information (e.g.,
student records).
✅ Flexible Data Storage: When handling dynamic data.
✅ Avoiding Index-Based Access: When keys are more
meaningful than indices.