Python Dictionaries, Enumerate and Slicing, ECE 20875 – Study Notes
offline

Difficulty: Beginner to Intermediate | Prerequisites: Python Lists, Loops and Functions study notes

Big Picture

Dictionaries are Python's go-to structure for labelled data, which makes them central to data science. This material covers how to group list elements into dictionary buckets using patterns like modular indexing and enumerate(), then how to query those buckets with nested loops and conditions. These are the same patterns you will use when organising real datasets by category, day-of-week, or any other grouping variable. You should be comfortable with lists, for-loops, and basic function writing before working through this.

TL;DR

Use dictionary comprehensions to initialise empty buckets, enumerate() to track both index and value while looping, and step-slicing or modular arithmetic to distribute list elements across keys. Counting entries that meet a threshold is a nested-loop-plus-conditional pattern.


Key Terms

Dictionary (dict)

An unordered collection of key-value pairs, written with curly braces. Think of it as a labelled filing cabinet: you look things up by name (the key), not by position.

Dictionary comprehension

A one-line way to build a dictionary. {day: [] for day in days} creates a dict with each weekday as a key and an empty list as its value. In simple terms, it is a shortcut for a loop that populates a dictionary.

enumerate()

A built-in that wraps an iterable and returns pairs of (index, value) on each iteration. for i, day in enumerate(days) gives you both the position and the element without maintaining a separate counter.

Step slicing (seq[start::step])

Extracts every step-th element from a list starting at index start. visits[0::7] grabs every Monday's value from a daily list. In simple terms, it lets you skip through a list at regular intervals.

Nested loop

A loop inside another loop. Used here to iterate over each weekday key in the dictionary, then over each value in that key's list.

Threshold

A cutoff value used to decide whether a data point qualifies. In count_busy_days, any visit count greater than or equal to the threshold is counted.


Core Content

Bucketing List Data by Weekday

The function bucket_visits_by_day(visits) takes a flat list of daily customer counts (starting on Monday) and groups them into a dictionary keyed by day name.

  • Initialise the dictionary: use a comprehension {day: [] for day in days} where days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]. Every key starts with an empty list.

  • Map indices to days with enumerate(): looping for i, day in enumerate(days) gives you i = 0 for Monday, i = 1 for Tuesday, and so on.

  • Two equivalent approaches to filling the buckets:

    • Step slicing: visits_dict[day] = visits[i::7] grabs every 7th element starting from index i. This is the cleanest one-liner.

    • Explicit loop: for j in range(i, len(visits), 7): visits_dict[day].append(visits[j]) does the same thing manually.

The key insight is that index 0 is Monday, index 7 is the next Monday, index 14 is the Monday after that, and so on. The pattern i, i+7, i+14, ... is exactly what range(i, len(visits), 7) or visits[i::7] produces.

Counting Entries Above a Threshold

The function count_busy_days(visits_dict, threshold) counts how many weekday entries meet or exceed a threshold.

  • Restrict to weekdays only: define weekday_list = ["Mon", "Tue", "Wed", "Thu", "Fri"]. Saturday and Sunday are excluded.

  • Nested loop: the outer loop iterates over each weekday name, the inner loop iterates over each count in that day's list.

  • Condition: if i >= threshold: count += 1 increments the counter for each qualifying entry.

  • Return the total count.

Note that the question counts individual entries, not unique days. If Monday has two values [70, 80] and both are above the threshold, that contributes 2 to the count, not 1.

Dictionary Comprehension Patterns

Dictionary comprehensions follow the form {key_expr: value_expr for item in iterable}. Common uses in this course:

  • Initialising with empty lists: {day: [] for day in days}

  • Initialising with zeros: {day: 0 for day in days}

  • Filtering: {k: v for k, v in d.items() if v > threshold}


Formulas and Key Code Patterns

Bucketing pattern (step-slice version)

def bucket_visits_by_day(visits):
    days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
    visits_dict = {day: [] for day in days}
    for i, day in enumerate(days):
        visits_dict[day] = visits[i::7]
    return visits_dict

Counting pattern (nested loop)

def count_busy_days(visits_dict, threshold):
    weekday_list = ["Mon", "Tue", "Wed", "Thu", "Fri"]
    count = 0
    for day in weekday_list:
        for i in visits_dict[day]:
            if i >= threshold:
                count += 1
    return count

Common Misconceptions

  • Using weekday_list[day] instead of visits_dict[day]. The exam answer key contains a bug here: the inner loop should iterate over visits_dict[day] (the dictionary of visit counts), not weekday_list[day] (which would try to index a list with a string and raise a TypeError).

  • Forgetting that step slicing can return an empty list. If the visits list is shorter than 7 elements, some days will have no entries. visits[5::7] on a 5-element list returns [], which is fine.

  • Counting unique days instead of individual entries. The function counts every entry that meets the threshold, not the number of distinct days. Monday with [70, 80] and threshold 40 contributes 2, not 1.

  • Including weekends in the count. The count_busy_days function only considers Mon through Fri. Using all seven days is a common mistake.


Why It Matters / Exam Flags

  • ⚠️ The exam gives you a partially written function and asks you to fill in the loop body. Know both the step-slice and explicit-loop approaches.

  • ⚠️ enumerate() is explicitly hinted in the exam question. If you see that hint, use it.

  • ⚠️ Be careful about which data structure you are indexing. Dictionaries use string keys; lists use integer indices. Mixing them up causes runtime errors.

  • ⚠️ The weekday-vs-all-days distinction is a deliberate trap. Read the question carefully.

Quick Self-Test

  1. True or False: {day: [] for day in ["A", "B"]} creates {"A": [], "B": []}.

  1. What does enumerate(["Mon", "Tue", "Wed"]) produce on its first iteration?

  1. Fill in the blank: visits[2::7] returns every ___th element starting from index ___.

  1. True or False: visits_dict["Mon"] returns a single integer.

  1. If visits_dict = {"Mon": [10, 80], "Tue": [20]}, how many times does the inner loop run when the outer loop is on "Mon"?

Answers: 1. True. 2. (0, "Mon"). 3. 7th, 2. 4. False (it returns a list of integers). 5. Twice (once for 10, once for 80).


Practice Q&A

Q: Given visits = [10, 20, 30, 40, 50, 60, 70, 80, 90], what does bucket_visits_by_day(visits) return for the key "Mon"?

A: [10, 80]. Index 0 is the first Monday (10), and index 7 is the next Monday (80).

Q: Why does the count_busy_days function define a separate weekday_list instead of using all the keys in visits_dict?

A: Because the function should only count weekdays (Mon through Fri), not weekends. Using visits_dict.keys() would include Sat and Sun.

Q: What is the output of count_busy_days(visits_dict, 40) given visits_dict = {"Mon": [70,80], "Tue": [50,90], "Wed": [30], "Thu": [40], "Fri": [50], "Sat": [60], "Sun": [70]}?

A: 6. Mon contributes 2 (70 ≥ 40, 80 ≥ 40), Tue contributes 2 (50 ≥ 40, 90 ≥ 40), Wed contributes 0 (30 < 40), Thu contributes 1 (40 ≥ 40), Fri contributes 1 (50 ≥ 40). Total = 6.

Q: Write an alternative one-liner for visits_dict[day] = visits[i::7] using range() and append().

A: for j in range(i, len(visits), 7): visits_dict[day].append(visits[j])

Connections to Other Topics

This connects directly to higher-order functions (filter, map, reduce) because count_busy_days is doing manually what filter() with a lambda could do in one line. Dictionary comprehensions are also the foundation for grouping operations you will see later with pandas groupby(). The modular-indexing pattern (every Nth element) shows up again when working with time-series data.

Related Terms / Search Tags

Python dictionary, dict comprehension, enumerate, step slicing, modular indexing, nested loop, threshold filter, weekday grouping, bucket pattern, key-value pair, ECE 20875, Python for Data Science, Purdue