Coding Now – Best AI & Full Stack Courses in Delhi NCR | 100% Placement
Limited Offer: Get 50% OFF on AI & Full Stack Courses
📞 Call Now: +91 9667708830
Back to Python Notes
Topic #10

Dictionary in Python

What Is a Dictionary?

A dictionary stores data as key-value pairs, giving you fast lookups by key instead of by position. Dictionaries are written with curly braces {} using key: value syntax.

student = {
    "name": "Aman",
    "course": "Data Science",
    "fee_paid": 12000
}

Accessing Values

print(student["name"])              # Aman
print(student.get("course"))        # Data Science
print(student.get("phone", "N/A"))  # N/A — safe default if key doesn't exist

Tip: use .get() instead of square brackets when a key might not exist — it avoids a KeyError.

Adding and Updating Values

student["phone"] = "9818523125"     # add new key
student["fee_paid"] = 24000          # update existing key

Removing Items

student.pop("phone")        # removes key and returns its value
del student["fee_paid"]      # removes key
student.clear()               # empties the whole dictionary

Looping Through a Dictionary

student = {"name": "Aman", "course": "Python"}

for key in student:
    print(key, "→", student[key])

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

for value in student.values():
    print(value)

Checking If a Key Exists

if "course" in student:
    print("Course found:", student["course"])

Dictionary Comprehension

squares = {x: x * x for x in range(1, 6)}
print(squares)   # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Nested Dictionaries

students = {
    "STU-0001": {"name": "Aman", "course": "Python"},
    "STU-0002": {"name": "Riya", "course": "Data Science"}
}
print(students["STU-0001"]["name"])   # Aman

Key Takeaways

  • Dictionaries map unique keys to values and preserve insertion order (Python 3.7+)
  • Use .get() for safe access with a fallback default
  • .items(), .keys(), and .values() are the go-to methods for looping
  • Keys must be immutable types (strings, numbers, tuples) — lists cannot be used as keys

Want to go beyond the notes?

Join CodingNow's Python course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available
💬 Talk to Advisor
1
WhatsApp

Latest from Our Blog

Insights on AI, Data Science, Full Stack & Career

View All Articles →