How to Parse Data Into Dictionaries and Sets in Python

Parses raw student strings into a dictionary of lists and finds unique courses using a set.

Easy Python 3.9+ Aug 9, 2026 Dictionaries & sets 12 views 0 copies

Python code

20 lines
Python 3.9+
from collections import defaultdict

def parse_students(raw_data):
    """Parse raw student strings into a dictionary of lists."""
    parsed = defaultdict(list)
    for entry in raw_data:
        name, _, course = entry.partition(":")
        parsed[course.strip()].append(name.strip())
    return dict(parsed)

def find_unique_courses(student_dict):
    """Return sorted set of all course names."""
    return sorted(set(student_dict.keys()))

if __name__ == "__main__":
    raw = ["Alice: Math", "Bob: Science", "Carol: Math", "Dave: History"]
    students = parse_students(raw)
    print("Parsed students:", students)
    print("Unique courses:", find_unique_courses(students))
    print("Math students:", students.get("Math", []))

Output

stdout
Parsed students: {'Math': ['Alice', 'Carol'], 'Science': ['Bob'], 'History': ['Dave']}
Unique courses: ['History', 'Math', 'Science']
Math students: ['Alice', 'Carol']

How it works

The defaultdict(list) automatically creates an empty list for each new course key, so you can append without checking if key in dict. The partition(":") method splits each raw string at the first colon and returns a three-tuple (before, separator, after); we ignore the separator with _. Using strip() removes surrounding whitespace from both names and course names. Converting the defaultdict to a regular dict at the end gives a clean, serializable structure. The set of keys gives unique course names, and sorted returns them in alphabetical order.

Common mistakes

  • Using `split(':')` instead of `partition(':')` and then unpacking a variable-length list breaks if there are extra colons.
  • Forgetting to strip whitespace from the parsed name or course, leaving hidden spaces in output.
  • Assuming the order of a set is meaningful; always sort when you need a predictable order.
  • Using a plain dict instead of `defaultdict` and then hitting a KeyError when a course is new.

Variations

  1. Use `dict.setdefault` to avoid importing defaultdict: `parsed.setdefault(course, []).append(name)`.
  2. Use a dict comprehension with `collections.Counter` if you only need counts, not full student lists.

Real-world use cases

  • Grouping log entries by error code or severity for a monitoring dashboard.
  • Parsing CSV rows into per-category lists for ingredient lists or inventory grouping.
  • Building a search index that maps each tag to a list of matching document IDs.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.