Python Data Structures
Python Dictionaries
A dictionary stores data as key-value pairs, letting you look up a value instantly by its unique key instead of searching by position.
Creating a Dictionary
You create a dictionary with curly braces, writing each key and value separated by a colon. Keys must be unique and immutable, such as a string, number, or tuple.
student = {
"name": "Aarav",
"age": 21,
"course": "B.Tech"
}
print(student)Accessing Values
Access a value with square-bracket key lookup, or use get(), which returns None (or a default you supply) instead of raising an error when the key is missing.
student = {"name": "Aarav", "age": 21}
print(student["name"]) # Aarav
print(student.get("city")) # None
print(student.get("city", "NA")) # NAAdding, Updating and Deleting
Assign to a new key to add it, or to an existing key to update its value. del and pop() remove a key — pop() also returns the value that was removed, which is handy inside functions.
student = {"name": "Aarav", "age": 21}
student["age"] = 22 # update
student["city"] = "Delhi" # add
del student["city"] # delete
age = student.pop("age") # remove and return
print(student, age)Iterating Over a Dictionary
keys() returns all keys, values() returns all values, and items() returns key-value pairs — items() is the most common choice inside a for loop.
student = {"name": "Aarav", "age": 21, "course": "B.Tech"}
for key, value in student.items():
print(key, "->", value)Why Use a Dictionary?
- Fast lookup by a meaningful key instead of a numeric index.
- Modelling real-world records, like a JSON API response or a database row.
- Counting occurrences, grouping data, or building simple caches.
Since Python 3.7, dictionaries remember insertion order, so looping over them gives keys in the order you added them.
