🐍
Syllabus / Python Programming / Phase 3: Lists, Tuples, Dictionaries, Sets (Days 11–15)
Intermediate

Dictionaries: Key-Value Pairs and Comprehensions

📂 Phase 3: Lists, Tuples, Dictionaries, Sets (Days 11–15) · Python Programming

A dictionary stores data as key-value pairs, letting you look up a value instantly by its associated key rather than by numeric position. Dictionaries are one of the most heavily used data structures in real Python code, from configuration settings to API responses (which are essentially nested dictionaries once parsed from JSON).

Creating a Dictionary

student = {
    "name": "Vishwas",
    "age": 22,
    "city": "Bengaluru"
}

empty_dict = {}

Accessing Values

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

print(student["name"])         # Vishwas
# print(student["grade"])      # KeyError — key does not exist

print(student.get("grade"))           # None — no error, just returns None
print(student.get("grade", "N/A"))    # N/A — returns a custom default instead
.get() is almost always the safer choice over direct bracket access when a key might not exist, since it never raises an exception — you control exactly what comes back instead.

Adding and Updating Values

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

student["city"] = "Bengaluru"   # adds a new key
student["age"] = 23              # updates an existing key
print(student)   # {'name': 'Vishwas', 'age': 23, 'city': 'Bengaluru'}

Removing Items

MethodEffect
del dict[key]Removes the key; raises KeyError if missing
.pop(key)Removes the key AND returns its value
.popitem()Removes and returns the last inserted key-value pair
.clear()Empties the entire dictionary
student = {"name": "Vishwas", "age": 22, "city": "Bengaluru"}
age = student.pop("age")
print(age)        # 22
print(student)    # {'name': 'Vishwas', 'city': 'Bengaluru'}

Looping Through a Dictionary

student = {"name": "Vishwas", "age": 22, "city": "Bengaluru"}

for key in student:               # loops through KEYS by default
    print(key)

for key, value in student.items():  # loops through key-value PAIRS together
    print(f"{key}: {value}")

for value in student.values():     # loops through VALUES only
    print(value)

Checking If a Key Exists

student = {"name": "Vishwas", "age": 22}
print("name" in student)    # True  — checks KEYS, not values
print("Vishwas" in student) # False — "Vishwas" is a value, not a key

Nested Dictionaries

students = {
    "s1": {"name": "Vishwas", "age": 22},
    "s2": {"name": "Priya", "age": 21}
}

print(students["s1"]["name"])   # Vishwas

Dictionary Comprehension

# Traditional approach
squares = {}
for n in range(1, 6):
    squares[n] = n ** 2
print(squares)   # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

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

Dictionary Comprehension With a Condition

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

Comprehensions Across All Four Data Structures — A Quick Comparison

StructureSyntaxExample
List[expr for item in iterable][n*2 for n in range(5)]
Set{expr for item in iterable}{n*2 for n in range(5)}
Dictionary{key: value for item in iterable}{n: n*2 for n in range(5)}
Generator(expr for item in iterable)(n*2 for n in range(5))

Notice that list and set comprehensions look almost identical except for the bracket type — the difference between [] and {} entirely determines which data structure you get back.

Why Dictionaries Are So Fast

Just like sets, dictionaries are built on a hash table internally — looking up a value by its key is close to instant (O(1) on average), regardless of how many items the dictionary holds, which is dramatically faster than searching through a list item by item.

Interview tip: "What is the time complexity of dictionary lookups?" is one of the most common Python fundamentals questions — the answer is O(1) average case due to hashing, though in rare worst-case scenarios involving hash collisions it can degrade to O(n); being able to state both the average and worst case shows real depth of understanding.