Andromeda
Note

Dictionaries (Python)

Definition

A collection of key-value pairs, where each unique key is mapped to a specific value. In Python, dictionaries are defined using curly braces {} and are highly flexible, dynamic structures.

Why It Matters

Dictionaries provide the O(1)O(1) lookup speed that makes modern software scalable; without this associative mapping, every data-intensive application would grind to a halt. They are the fundamental bridge between human-readable labels and computer-stored values.

Core Concepts

  • Key-Value Mapping: Data is accessed via arbitrary keys (strings, integers, etc.) rather than numerical indices.
  • Unordered Nature: While modern Python (3.7+) remembers insertion order, dictionaries are fundamentally unordered collections. You cannot slice them or access them via integer indices like spam[0] unless 0 is an explicit key.
  • Equality Logic: Two dictionaries are considered equal (==) if they contain the same key-value pairs, regardless of the order in which they were added.
  • View Objects: The methods .keys(), .values(), and .items() return “view objects” (dict_keys, etc.) that are dynamic, iterable, and can be converted to lists with list().
  • Safe Methods:
    • .get(key, default): Returns the value for key, or default if the key is missing.
    • .setdefault(key, default): An Atomic Check-and-Set. If the key doesn’t exist, it sets it to the default. It always returns the value (either existing or newly set).
  • Membership: key in my_dict is the idiomatic way to check for existence (defaults to checking keys).
capitals = {"USA": "Washington D.C.", "France": "Paris"}
capitals["Germany"] = "Berlin"

# Safe access with get()
capital = capitals.get("Japan", "Not found")

for country, city in capitals.items():
    print(f"{country}: {city}")

Connected Concepts