Skip to content

Lists and Maps

You'll learn when to reach for a list, a dictionary or a set, which are the three containers your language ships with, so a lot of your code can get shorter on its own.

About

Most beginner code is slow and long because it uses a list where a dictionary belonged. This badge teaches you the three containers your language gives you and when each one wins. The test is simple. If you're looping through something to find an item, you probably wanted a map. If you're checking for duplicates, you wanted a set. Once you can feel the difference, a lot of your code gets shorter on its own.

At a glance

Per requirement
15 XP
Completion bonus
75 XP
Requirements
6
Takes
One weekend
Skill level
Beginner (done it a few times)
Cost
Free
Supplies
Nothing special
Where
At home
Other people
On your own

Requirements

  1. 1
    Count how often each word appears in a text file of at least 5,000 words. Read the file, split it on whitespace, lowercase everything, strip the punctuation, and count into a dictionary. Then print the top 20. Any public domain book works, and Project Gutenberg has thousands as plain text. Take a screenshot of the top 20. Photo
  2. 2
    Remove duplicates from a list of 10,000 items two ways, and time both. Do it once with a nested loop that checks each item against all the others, and once with a set. The slow version may take seconds while the set takes almost nothing, and that gap is the whole lesson. Take a screenshot of both timings. Photo
  3. 3
    Group a list of records by one field. Make 50 fake people with a name, a city and an age, or load a CSV if you have one. Group them by city into a dictionary of lists, then print each city with its count. Take a screenshot of the grouped output. Photo
  4. 4
    Sort a list of dictionaries by two keys at once. Sort by age descending, then by name ascending. Use your language's built-in sort with a key function. If you found yourself writing your own sort here, you worked too hard. Take a screenshot of the sorted output. Photo
  5. 5
    Build a nested structure three levels deep and pull one value out of it. Try a dictionary of lists of dictionaries, like a school with classes with students. Reach in and print one student's grade, then print the whole thing as JSON. Take a screenshot of the JSON and the single value. Photo
  6. 6
    Write one sentence for each container on when you'd reach for it. One line each for list, dictionary and set, in your own words, with an example from this badge. Take a photo of the note or a screenshot of the text file. Photo