Python Dictionaries

Key-value pairs.

✍️ 3 exercises + code challenge in this lesson

A dictionary stores data as key: value pairs:

student = {"name": "Sara", "age": 22}

  • Read: student["name"] or student.get("city", "N/A") (no error if missing).
  • Add or change: student["city"] = "Lahore"
  • Remove: pop("age"), del student["age"]
  • Loop: keys(), values(), items()
  • Merge: a | b or a.update(b)

Dictionaries can be nested to represent complex data, just like JSON.

Key Takeaways: Python Dictionaries

Mastering Python Dictionaries helps you write clean and reliable Python code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

Python Dictionaries Code Example

Python
student = {"name": "Sara", "age": 22, "skills": ["python", "sql"]}

student["city"] = "Lahore"
student["age"] += 1
print(student["name"], "is", student["age"])
print("Country:", student.get("country", "Pakistan"))

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

students = {
    "s1": {"name": "Ali", "marks": 81},
    "s2": {"name": "Hina", "marks": 94},
}
top = max(students.values(), key=lambda s: s["marks"])
print("Top student:", top["name"])
Free sign-in required · Google login available

Python Dictionaries Practice Exercises

Check what you learned in “Python Dictionaries”.

/ 3 solved
Fill in the blank

Read a key without an error when it is missing.

city = person.("city", "Unknown")
✓ Correct! Not quite. Try again.
Multiple choice

Which method loops over key-value pairs?

✓ Correct! Not quite. Try again.
Code challenge

Add the key "city" with value "Multan" to the dictionary and print the dictionary.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services