Lesson 13 of 30

In progress

Course progress

Python

Dictionaries: values with names

Map keys to values, read them safely with get(), loop over items, and count occurrences without writing one branch per case.

A list answers "what is at position three". A dictionary answers "what is the price of the large shirt". Once data has labels rather than positions, a dictionary is the natural home.

What you will learn

  • Create dictionaries and read values without crashing on missing keys.
  • Add, update and delete entries.
  • Loop over keys, values and pairs, and count occurrences.

Keys and values

A dictionary stores pairs. The key is the label, the value is the data, and both live inside curly braces.

Code
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



Press Run to see the output.

Lookup by key is fast even in a large dictionary, because Python hashes the key instead of scanning. Keys must be immutable: strings, numbers and tuples work; lists do not. Values can be anything, including lists and other dictionaries.

The in operator checks keys, not values. "pens" in stock asks whether the label exists; to ask whether a count appears, you have to search stock.values(), which scans and is much slower.

Reading a missing key with square brackets raises KeyError. That is useful when the key must exist, and annoying when it might not. get() handles the second case.

Code
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



Press Run to see the output.

get returns None when the key is absent, or the default you pass. Use get for optional data and square brackets when a missing key is a real bug you want to hear about.

Add, update, delete

Assignment adds a key that does not exist and overwrites one that does. del removes a pair, and pop removes it while returning the value.

Code
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



Press Run to see the output.

pop accepts a default too: stock.pop("markers", 0) avoids a KeyError when the key may be absent. update merges another dictionary into this one, which is handy for applying a batch of changes.

Values can themselves be dictionaries, which is how you model a record with sections. user["address"]["city"] reads the city from a nested address, and each bracket is one lookup. When a level may be missing, chain get calls with an empty dictionary as the default: user.get("address", {}).get("city", "Unknown"). That expression never raises, at the cost of hiding a structural problem you might prefer to see.

Looping over a dictionary

Iterating a dictionary gives keys by default. .keys(), .values() and .items() make the intent explicit, and .items() is what you usually want.

Code
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



Press Run to see the output.

Unpacking name, count from each pair is the idiom to learn. Since Python 3.7, dictionaries keep insertion order, so output is predictable; do not confuse that with sorting. To process keys in alphabetical order, loop over sorted(stock).

Counting is the killer feature

The pattern below replaces what would otherwise be a chain of if statements, one per possible value.

Code
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



Press Run to see the output.

Read counts.get(word, 0) as "the current count, or zero if this is the first time". Then add one and store it back. That single line is worth memorising; it appears in word counts, vote tallies and inventory checks.

Changing a dictionary’s size while looping over it raises RuntimeError: dictionary changed size during iteration. Collect the keys to remove first, then delete them: for key in [k for k in stock if stock[k] == 0]: del stock[key]. The list comprehension takes a snapshot, so the loop is safe.

Count how many times each word appears in a sentence, ignoring case and punctuation, then print the three most common words. sorted with a key function gets you the ranking without importing anything.

Show solution
Code
Code runs on the Java or .NET runtime, not in a browser tab. Copy this example into your editor and run it there.



Press Run to see the output.

split() breaks on whitespace, and stripping the full stop stops hot. becoming a separate key from hot. The lambda sorts by the count, not the word.

Recap

  • Dictionaries map immutable keys to values, with fast lookup.
  • get(key, default) reads optional keys without raising; items() loops over pairs.
  • counts[key] = counts.get(key, 0) + 1 is the standard counting idiom.

Next, you will meet the two smaller collections: tuples for fixed records and sets for uniqueness.

Are dictionaries ordered?
Yes, insertion order is preserved from Python 3.7 onward. That makes output predictable, but it is not sorted order. Use sorted() on the keys when alphabetical order matters.
Can a dictionary key be a tuple?
Yes, if every element of the tuple is immutable. A tuple of strings works; a tuple containing a list does not, because the list could change and break the hashing.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.