Python Dictionary
What is a Python Dictionary?
A Python dictionary is an unordered, mutable collection used to store data in key-value pairs. Unlike lists or tuples, which are indexed by numbers, dictionaries use keys to access their elements, making them ideal for scenarios where you need to map unique identifiers to specific values.
Key Features of Dictionaries
- Unordered: The order of items is not guaranteed.
- Mutable: You can modify, add, or delete items.
- Keys Must Be Unique: No duplicate keys are allowed.
- Fast Lookups: Accessing a value using its key is highly efficient.
Creating a Dictionary
A dictionary is defined using curly braces {}
with key-value pairs separated by colons :
.
# Example: Creating a dictionary
student = {
"name": "Rahul",
"age": 25,
"course": "MCA"
}
print(student)
Output:
{'name': 'Rahul', 'age': 25, 'course': 'MCA'}
Accessing Values
You can access dictionary values using their corresponding keys.
# Accessing values
print(student["name"]) # Output: Rahul
print(student.get("age")) # Output: 25
If a key does not exist, .get()
returns None
instead of raising an error.
Adding and Updating Items
Use assignment to add new key-value pairs or update existing ones.
# Adding and updating
student["grade"] = "A" # Adding a new key-value pair
student["age"] = 26 # Updating an existing key
print(student)
Output:
{'name': 'Rahul', 'age': 26, 'course': 'MCA', 'grade': 'A'}
Removing Items
You can remove items using methods like pop()
and del.
# Removing items
student.pop("grade") # Removes key 'grade'
del student["age"] # Deletes key 'age'
print(student)
Output:
{'name': 'Rahul', 'course': 'MCA'}
Iterating Through a Dictionary
You can iterate over keys, values, or key-value pairs.
# Iterating over a dictionary
for key, value in student.items():
print(f"{key}: {value}")
Output:
name: Rahul
course: MCA
Nested Dictionaries
Dictionaries can also contain other dictionaries, making them useful for hierarchical data.
# Nested dictionary
students = {
"101": {"name": "Rahul", "age": 25},
"102": {"name": "Ananya", "age": 24}
}
print(students["101"]["name"]) # Output: Rahul