PyForge · Python practice library
All topics

Topic 08 of 17

Dictionaries

Key-value mappings — fast lookups and structured data.

get/setdefault
Dict comprehensions
Merging (|)
Iteration

Basic

2 programs

Program 1

Create & access dict

Basic

Basic dictionary operations.

python
student = {"name": "Riya", "age": 21, "grade": "A"}
print(student["name"])
student["age"] = 22
student["city"] = "Mumbai"
print(student)

Program 2

Iterate items

Basic

Walk keys and values together.

python
prices = {"apple": 30, "banana": 10, "mango": 50}
for item, price in prices.items():
    print(f"{item}: ₹{price}")

Intermediate

2 programs

Program 1

Dict comprehension

Intermediate

Build a dict in a single expression.

python
squares = {x: x * x for x in range(1, 6)}
print(squares)

Program 2

Merge dictionaries

Intermediate

Use the | operator (Python 3.9+).

python
a = {"x": 1, "y": 2}
b = {"y": 20, "z": 3}
print(a | b)

Advanced

1 program

Program 1

Group by key

Advanced

Group items using defaultdict.

python
from collections import defaultdict

people = [("dev", "Asha"), ("design", "Ravi"), ("dev", "Maya"), ("design", "Sam")]
teams = defaultdict(list)
for team, name in people:
    teams[team].append(name)
print(dict(teams))