Dictionary

A collection of key-value pairs for looking up values by key.

A dictionary stores data as key/value pairs inside curly braces, like {'name': 'Sam'}. Instead of a numeric position you look things up by key. Keys must be unique, so assigning to an existing key overwrites its value, and .get() returns a fallback you choose when a key might be missing.

Example
ages = {"Sam": 30, "Ada": 36}
print(ages["Ada"])         # look up a value by its key
ages["Lee"] = 25           # add a new pair
ages["Sam"] = 31           # reassign an existing key
print(ages.get("Max", 0))  # a default when the key is absent
Output
36
0

Where this shows up in real Python

Dictionaries map keys to values: counting how often things occur, holding configuration, or modelling JSON-like records you look up by name.

Commonly used Dictionary tools

dict is a built-in type with its own methods:

  • .get(key, default) — read safely instead of raising KeyError
  • .keys() / .values() — view all keys or all values
  • .items() — loop over key/value pairs together
  • .setdefault(key, default) — read a key, inserting a default if missing
  • .update(other) — merge another dict’s pairs in
  • .pop(key, default) — remove a key and return its value

Official documentation: Python Tutorial: Dictionaries

Related lessons

Related terms