Dictionaries in Python

A dictionary stores data in key–value pairs. It is used when you want to associate one value with another.

💡 Dictionaries are written using curly braces { } with keys and values separated by a colon.

Creating a Dictionary

student = {
  "name": "Khushi",
  "age": 18,
  "city": "Pune"
}

print(student)

Accessing Values

print(student["name"])
print(student["age"])

Using get()

The get() method prevents errors if a key does not exist.

print(student.get("city"))
print(student.get("marks", "Not available"))

Adding & Updating Items

student["marks"] = 92
student["age"] = 19

print(student)

Removing Items

student.pop("city")
del student["age"]

print(student)

Looping Through a Dictionary

for key, value in student.items():
    print(key, ":", value)

Keys, Values & Items

print(student.keys())
print(student.values())
print(student.items())

When to Use Dictionaries?

  • Storing structured data
  • Fast data lookup
  • Mapping names to values

Practice Exercises

  1. Create a dictionary for a book
  2. Add price and author
  3. Update the price
  4. Loop and print all key–value pairs