Dictionaries, Sets and Comprehensions
Look things up by name with dictionaries, keep collections free of duplicates with sets, build new lists, dictionaries and sets in one readable line with comprehensions, and sort anything by the value you choose. Then you'll write a recipe app's pantry: what you have, what a recipe needs and the shopping list in between.
Updated
Dictionaries in Python
- Dictionaries: Looking Things Up by Name (Novice): A dictionary stores each value under a key you choose, so a program finds a value by its name instead of its position, and adds, changes and removes entries as the data changes.
- Looping Through Dictionaries and Nested Data (Apprentice): A for loop goes through a dictionary's keys, items(), keys() and values() give its pairs, its keys or its values, and lists of dictionaries and dictionaries of lists hold whole tables of data, the shape CSV files and web APIs give you.
Sets in Python
- Sets: No Duplicates Allowed (Apprentice): A set holds each value once and in no order, so it removes duplicates, checks quickly whether something is there, and compares two collections with union, intersection and difference.
Comprehensions and Sorting
- Comprehensions: New Lists in One Line (Apprentice): A comprehension builds a new list, dictionary or set from another collection in one line, written as what goes in, for each item, if a condition holds, and replaces the empty-list-and-append loop whenever the whole job is building one collection.
- Sorting with key and lambda (Journeyman): sorted() takes a key, a function it calls on each item to get the value to compare, so a short lambda can sort recipes by their minutes or a dictionary's entries by their values, from largest to smallest with reverse=True.
Exercise: Pantry and Shopping List
- Exercise: Pantry and Shopping List (Apprentice): Write the five functions behind a recipe app's pantry, with a dictionary of amounts, sets of ingredients, a set difference, comprehensions and sorting with a key, and let pytest's tests check each one.
Up Next: Building Real Programs
- Up Next: Building Real Programs (Apprentice): Look back at what Module 2 taught, functions, lists, tuples, dictionaries, sets, comprehensions and sorting, try a grade book of your own that uses all of it, and see what Module 3 adds, files, packages, error handling and classes.