Week 1 • Thursday

Block 8: Dictionaries for Structured Data

Use dicts to store labeled, key-value data.

Concepts

Code Examples

Dict basics

person = {'name': 'Alice', 'age': 25}
print(person['name'])
print(person.get('city', 'Unknown'))
person['city'] = 'NYC'

Looping over dict

scores = {'a': 1, 'b': 2, 'c': 3}
for k, v in scores.items():
    print(f'{k}: {v}')

Exercise

Represent 3 students as dicts with name and marks. Compute class average. Build a word-frequency counter for a short sentence.

Solution
students = [
    {'name': 'Alice', 'marks': 85},
    {'name': 'Bob', 'marks': 72},
    {'name': 'Carol', 'marks': 90}
]
class_avg = sum(s['marks'] for s in students) / len(students)
print(f'Class average: {class_avg:.1f}')

sentence = 'the cat sat on the mat'
words = sentence.split()
freq = {}
for w in words:
    freq[w] = freq.get(w, 0) + 1
print(freq)

Practice Problems

Problem 1: Merge two dicts: d1 and d2. If same key, keep d2's value.

Hint: d1.update(d2) or {**d1, **d2}

Problem 2: Get all keys from a dict as a sorted list

Hint: sorted(d.keys())

Application

Dicts map IDs to records, config keys to values, and category names to counts—essential for structured data.

Case Study

A config file is loaded as a dict: {'batch_size': 32, 'epochs': 10}. The training script reads config['batch_size'] instead of hardcoding.

Homework

Describe a real-world situation where a dictionary is more useful than a list.