Skip to content
CodeNest

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'?"

Python
Output
Ada Lovelace
Python
4 fields
— expected output; press Run to execute it yourself
Python
Output
None
not provided
True
KeyError — that key does not exist
— expected output; press Run to execute it yourself

Changing a dictionary

Assigning to a key sets it, whether or not it already existed.

Python
Output
{'theme': 'dark', 'font_size': 14, 'autosave': True}
{'theme': 'dark', 'autosave': True}
True {'theme': 'dark'}
— expected output; press Run to execute it yourself

Looping

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.

Python
Output
apples pears figs
12 0 7
apples    12  in stock
pears      0  OUT
figs       7  in stock
— expected output; press Run to execute it yourself

Counting 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.

Python
Output
the: 3
quick: 1
brown: 1
— expected output; press Run to execute it yourself

Exercise

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.

Python
Output

Press Run to execute this code.

Check your understanding

0/3 answered
  1. 1.What does {"a": 1}.get("b", 0) return?
  2. 2.What does looping for x in my_dict: give you?
  3. 3.Which is the correct way to add a new key?