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.
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.
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.
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.
2 · Watch
Take it off screen
Where it sits
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.