Write Python. Understand every error.

Starting Python in your browser…

Python basics · topic 13 of 25

Dictionaries

A dictionary stores pairs of keys and values, like a real dictionary stores words and meanings. You look up a value by its key, not by position.

prices = {"tea": 10, "samosa": 15}
print(prices["tea"])

You can add or change an entry with d[key] = value. Looking up a missing key causes a KeyError, so use d.get(key, default) when the key might not exist.

Loops over dictionaries are common. d.keys() gives the keys, d.values() the values, and d.items() both together.

for item, price in prices.items():
    print(item, price)

A dictionary is also the standard tool for counting: start each count at 0 with get, then add 1.

Key takeaways

  • A dictionary stores key and value pairs, and you look up a value by its key, not by its position.
  • d[key] = value adds or changes an entry.
  • d.get(key, default) is a safe lookup that does not fail when the key is missing.
  • d.items() gives keys and values together, and counting with get(key, 0) + 1 is a standard pattern.

Common mistakes

Practise with these programs

Share this page:

Ctrl + Enter to run
Line 1, column 1Tab indents 4 spaces. Press Esc then Tab to leave the editor.