PYTHON • Intermediate

Python Dictionaries

A dictionary is an ordered (since Python 3.7), mutable collection of key-value pairs. Dictionaries are the most-used data structure for storing structured data — from user profiles to API responses. Every key must be unique.

Creating a Dictionary

# Empty dict
empty = {}

# Basic dictionary
student = {
    "name": "Ankit",
    "age": 22,
    "course": "Python"
}

# Using dict() constructor
person = dict(name="Priya", age=20, city="Varanasi")

# From list of tuples
pairs = dict([("a", 1), ("b", 2)])
print(pairs)   # {'a': 1, 'b': 2}

Accessing Values

student = {"name": "Ankit", "age": 22, "course": "Python"}

# Bracket notation
print(student["name"])       # Ankit
print(student["age"])        # 22

# Using .get() — safer, returns None if key missing
print(student.get("name"))       # Ankit
print(student.get("city"))       # None
print(student.get("city", "N/A"))  # N/A (default value)
⚠ Important

student["city"] raises a KeyError if "city" doesn't exist. Use student.get("city") to avoid crashes.

Adding and Updating Items

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

# Add new key
student["city"] = "Varanasi"

# Update existing key
student["age"] = 23

# Update multiple keys
student.update({"course": "Python", "batch": "2026"})

print(student)

Removing Items

student = {"name": "Ankit", "age": 22, "course": "Python"}

# Remove specific key
del student["age"]

# Remove and return value
course = student.pop("course")
print(course)   # Python

# Remove last inserted (Python 3.7+)
name = student.popitem()

# Remove all
student.clear()

print(student)   # {}

Dictionary Methods

student = {"name": "Ankit", "age": 22, "course": "Python"}

# All keys
print(student.keys())       # dict_keys(['name', 'age', 'course'])

# All values
print(student.values())     # dict_values(['Ankit', 22, 'Python'])

# All key-value pairs
print(student.items())      # dict_items([('name', 'Ankit'), ('age', 22), ...])

# Length
print(len(student))         # 3

# Check if key exists
print("name" in student)    # True
print("city" in student)    # False

Looping Through a Dictionary

student = {"name": "Ankit", "age": 22, "course": "Python"}

# Loop through keys
for key in student:
    print(key)

# Loop through keys and values
for key, value in student.items():
    print(f"{key}: {value}")

# Output:
# name: Ankit
# age: 22
# course: Python

Nested Dictionaries

Dictionaries can contain other dictionaries — great for storing structured data like API responses.

students = {
    "s001": {"name": "Ankit", "age": 22, "course": "Python"},
    "s002": {"name": "Priya", "age": 21, "course": "Full Stack"},
    "s003": {"name": "Rahul", "age": 23, "course": "Digital Marketing"}
}

# Access nested value
print(students["s001"]["name"])   # Ankit
print(students["s002"]["course"]) # Full Stack

# Loop through nested dict
for sid, info in students.items():
    print(f"{sid} - {info['name']} ({info['course']})")

Dictionary Comprehension

A concise way to create dictionaries in one line.

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

# Only even numbers
evens = {x: x**2 for x in range(1, 11) if x % 2 == 0}
print(evens)     # {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}

Real-World Example — Student Record

student = {
    "name": "Ankit Kumar",
    "age": 22,
    "city": "Varanasi",
    "skills": ["Python", "HTML", "JavaScript"],
    "courses": {
        "python": 85,
        "dsa": 78,
        "web": 92
    }
}

print(f"Student: {student['name']}")
print(f"City: {student['city']}")
print(f"Skills: {', '.join(student['skills'])}")

# Average marks
total = sum(student["courses"].values())
avg = total / len(student["courses"])
print(f"Average marks: {avg:.1f}")
💡 Academy Tip

Since Python 3.7, dictionaries remember insertion order. This was a big deal — it means you can rely on the order of items when iterating.

📝 Try Yourself

Create a dictionary of 5 students with their names and marks. Print each student's name and marks. Then find and print the student with the highest marks. Finally, add a new student and remove the one with the lowest marks.

Quick Revision

  • Dictionaries store key-value pairs; keys are unique.
  • Created with {} or dict().
  • Access with d[key] or d.get(key).
  • Methods: keys, values, items, get, update, pop, popitem, clear.
  • Loop: for k, v in d.items().
  • Dictionary comprehension: {k: v for k, v in iterable}.
  • Ordered since Python 3.7.

Interview Questions

Q: Difference between d["key"] and d.get("key")?

A: d["key"] raises KeyError if the key doesn't exist. d.get("key") returns None (or a default value if provided) — much safer.

Q: Can a dictionary have duplicate keys?

A: No. Keys must be unique. If you assign to an existing key, the old value is overwritten.

Q: Can a list be a dictionary key?

A: No. Dictionary keys must be immutable (hashable). Lists, sets, and other dictionaries cannot be keys. Tuples and strings can be keys.

Q: How do you merge two dictionaries?

A: In Python 3.9+, use the | operator: d3 = d1 | d2. Alternatively, d1.update(d2) or {**d1, **d2} work in older versions.

Want to Master Python?

Join our Python course in Varanasi — practical classes and career support at our Sarnath centre.

Ask on WhatsApp
Chat with us