Data StructuresLesson 11 of 1916 min
Dictionaries
Look values up by name instead of position — the structure behind settings, records, and JSON.
By the end you will be able to
- Create dictionaries and read values by key
- Add, update, and delete entries safely
- Iterate over keys, values, and items
A dictionary maps keys to values. Where a list answers "what is at position 2?", a dict answers "what is stored under 'email'?"
Ada Lovelace
Python
4 fields
— expected output; press Run to execute it yourselfNone
not provided
True
KeyError — that key does not exist
— expected output; press Run to execute it yourselfChanging a dictionary
Assigning to a key sets it, whether or not it already existed.
{'theme': 'dark', 'font_size': 14, 'autosave': True}
{'theme': 'dark', 'autosave': True}
True {'theme': 'dark'}
— expected output; press Run to execute it yourselfLooping
Looping over a dict directly gives you its keys. Use .values() for values and .items() for both at once — .items() is the one you will want most often.
apples pears figs
12 0 7
apples 12 in stock
pears 0 OUT
figs 7 in stock
— expected output; press Run to execute it yourselfCounting with a dictionary
A dict is the natural tool for tallies. The .get(key, 0) + 1 idiom handles the "first time I have seen this" case without a special branch.
the: 3
quick: 1
brown: 1
— expected output; press Run to execute it yourselfExercise
Write count_letters(text) that returns a dict mapping each letter to how many times it appears. Ignore spaces, and treat upper and lower case as the same letter.
Press Run to execute this code.