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.
Python code
20 linesfrom 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
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
- Use `dict.setdefault` to avoid importing defaultdict: `parsed.setdefault(course, []).append(name)`.
- 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
More from Dictionaries & sets
- Build a Case-Insensitive Dict with a Wrapper Class in Python medium
- Build a defaultdict histogram of categories in Python easy
- Build adjacency dict graph from edges in Python easy
- Build an OrderedDict insertion order demo in Python 3 easy
- Check Invertible Mapping for Duplicate Values in Python easy
- Compare Two Dictionaries in Python easy
Keep learning
Related tutorials and quizzes for this topic.