LightMySky

Dictionaries: Values Found by Key

A collection where each value is stored under a key of the programmer's choosing instead of a position. Looking a value up by key stays fast however many pairs are stored.

No account needed. Progress saves in this browser.

What a learner can do afterwards

  • Build a dictionary, read a value by key, and add or replace a pair
  • Loop over keys and values to produce a summary such as a word count
  • Say when a dictionary suits the data better than a list, and when it does not

1 · Read

A dictionary stores pairs, each with a key and a value, like a word and its definition. You write pairs in curly braces, as in {"apple": "red", "banana": "yellow"}. To read a value, you ask by key: forecast["temp"] hands back 4. No two keys in one dictionary may match, since each key must point to exactly one value.

Try it together

To count words, you walk the sentence and tally each word under its own key. Start empty, then for each word either add it with a count of 1 or raise its count by 1. The .get() helper gives 0 for a word seen first, so counts[word] = counts.get(word, 0) + 1 never fails. One pass over a whole book still works the same way.

Point keys toward the question you will ask, because lookup runs key to value only. A phone book keyed by country finds a calling code, but finding the country from a code needs the reversed dict, as in {1: "US", 91: "IN"}. Before reading, test with in, since brackets on a missing key raise an error. Loop with keys(), values() or items() to sum a field across records.

Good to know

Pick a dictionary when you find things by name and a list when place or order matters. A list answers what sits third, while a dictionary answers what "temp" is. If you need both orders, you may need two structures, since one mapping runs a single way.

Keys name the values, lookup runs key to value, and tallies grow one pair at a time.

More to read

Dictionary basics

A dictionary is a way to store information in pairs. Each pair has a key and a value, kind of like a word and its definition in a real dictionary. You look up the key, and it hands back the value that goes with it.

In Python, you write a dictionary using curly braces, like this: {"apple": "red", "banana": "yellow"}. Here, "apple" and "banana" are keys, and "red" and "yellow" are their values.

No two keys in the same dictionary can be the same. Each key has to point to exactly one value, or things get confusing fast. That is the big difference between a dictionary and a list. In a list, you find things by counting positions, like first, second, or third. In a dictionary, you find things by name, so you do not need to know where something sits, just what it is called.

Data records

Sometimes you want to describe one real thing, like a weather forecast, using several pieces of information at once. A dictionary is great for this. Each key names a piece of information, and its value holds the answer.

For example: forecast = {"condition": "rain", "temp": 4, "precip": 6.2}. Now forecast["temp"] gives you 4 right away. It does not matter how many other keys are sitting in that same dictionary, the lookup is just as fast.

What if you need to describe many forecasts, like one for every day of the year? You put a bunch of these dictionaries together inside a list. Each dictionary is one record, and the list holds the whole collection of records.

Dictionary design patterns

Dictionaries only work one way: you give a key, and you get back its value. You cannot search a dictionary by value and ask for the matching key, at least not directly.

So before you build a dictionary, think about which direction you will actually need to look things up. Take calling_codes = {"US": 1, "IN": 91, "BR": 55, "KE": 254}. This makes sense because you will usually ask "what is the calling code for this country," not the other way around.

If your keys match how you plan to search, a dictionary saves you a lot of digging around. Pick keys based on what you will look up most often, not just what feels natural to list first.

Nested dictionaries and dictionary comprehension

A dictionary's values do not have to be simple numbers or words. A value can be another dictionary. This is called nesting, and it lets you group related information together.

For example, you might have one dictionary for a whole class, where each key is a student's name, and each value is a smaller dictionary holding that student's grades, like {"Sam": {"math": 90, "art": 85}}.

To reach a piece of information inside a nested dictionary, you look up the outer key first, then the inner key, one step at a time. So class["Sam"]["math"] gives you 90.

2 · Watch

Take it off screen

Print a worksheetA4 with an answer key page for grown-ups. No screen, no internet.

Where it sits

Then practise

8 questions wait behind this lesson, each with its answer explained. Every answer feeds the sky: stars light as they are learned, and dim when it is time to come back.

Spotted a problem on this page? Tell us
Dictionaries: Values Found by Key · Computing, ages 16 to 17 · LightMySky