Browse Python Topics ▼
Pick a Web Framework

Python Dictionaries and Hash Maps

📂 Data Structures & Collections 📘 Lesson 19 of 57

Master Python dictionaries—fast key-value mappings. Learn creation, safe lookup with .get(), iteration over keys/values/items, dictionary merging, and hash table mechanics.

When using lists or tuples, you access information by a numerical position: items[0], items[1], items[2].

In real life, however, humans rarely organize information by arbitrary index numbers. Imagine looking up a friend’s phone number: you don’t search for “person at index 142”; you search for their name.

Or imagine representing a user profile:

# Clumsy list: what does each number represent?
user = ["Alex Rivera", 29, "Engineer", "San Francisco", True]

If someone asks for Alex’s occupation, you have to remember that index 2 happens to be their job title. If someone adds a middle name at index 1, all subsequent indices break!

Python solves this with its most powerful, fundamental data structure: the Dictionary (dict).


1. What Is a Dictionary?

A dictionary is an unordered-by-nature, insertion-ordered collection of key-value pairs enclosed in curly braces {...}:

# A descriptive user profile
user = {
    "name": "Alex Rivera",
    "age": 29,
    "role": "Engineer",
    "city": "San Francisco",
    "is_active": True
}

print(user)
print("Total profile fields:", len(user))

Output:

{'name': 'Alex Rivera', 'age': 29, 'role': 'Engineer', 'city': 'San Francisco', 'is_active': True}
Total profile fields: 5

The Key-Value Mental Model

Think of a dictionary like an actual hardcover dictionary or a hotel key rack:

  • Key: The label on the hook (e.g. "room_101", "name", "user_id").
  • Value: The physical key or data hanging on that hook (e.g. "Keycard #8492", "Alex Rivera", 48291).

2. Reading, Adding, and Updating Values

Reading with Bracket Notation (dict[key])

user = {"name": "Alex", "role": "Engineer"}

print("User's name:", user["name"])
print("User's role:", user["role"])

Adding New Keys and Updating Existing Keys

Assignment syntax is identical for creating new keys and updating existing ones:

  • If the key already exists, Python updates its value.
  • If the key does not exist, Python adds the new key-value pair!
inventory = {"apples": 10, "bananas": 5}

# Update an existing key:
inventory["apples"] = 12

# Add a brand new key:
inventory["oranges"] = 8

print(inventory)

Output:

{'apples': 12, 'bananas': 5, 'oranges': 8}

3. The KeyError Trap and the Safe .get() Method

What happens if you try to access a key that does not exist?

user = {"name": "Alex"}

# DANGER: Crashes with KeyError!
# email = user["email"]

Python immediately halts with a KeyError: 'email'.

The Safe Solution: .get(key, default)

The .get() method attempts to retrieve the key. If the key exists, it returns the value. If the key is missing, it returns None (or a fallback value you supply) instead of crashing:

user = {"name": "Alex"}

# Safe retrieval: returns None if missing
email = user.get("email")
print("Email:", email)  # None

# Safe retrieval with custom fallback default:
theme = user.get("theme", "dark-mode")
print("Selected theme:", theme)  # dark-mode (used default!)

[!TIP] Use dict[key] when you expect the key to always be present and want your program to scream if it is missing. Use .get(key, default) when the key is optional or uncertain.


4. Deleting Key-Value Pairs

1. del dict[key]

Deletes the key-value pair permanently (raises KeyError if key is missing):

profile = {"name": "Sam", "temp_token": "xyz123"}
del profile["temp_token"]
print(profile)  # {'name': 'Sam'}

2. .pop(key, [default])

Removes the key and returns its value back to you:

session = {"user_id": 42, "auth_code": "secret"}
code = session.pop("auth_code")
print("Extracted auth code:", code)  # secret
print("Cleaned session:", session)   # {'user_id': 42}

3. .clear()

Empties all pairs from the dictionary:

cache = {"a": 1, "b": 2}
cache.clear()
print(cache)  # {}

5. Iterating Over Dictionaries

Dictionaries provide three distinct view methods for loops:

capitals = {"France": "Paris", "Japan": "Tokyo", "Brazil": "Brasília"}

# 1. Loop through KEYS (default behavior)
print("Countries:")
for country in capitals:
    print(f"  {country}")

# 2. Loop through VALUES
print("\nCapitals:")
for city in capitals.values():
    print(f"  {city}")

# 3. Loop through BOTH (keys and values) using .items() [BEST PRACTICE!]
print("\nCountry and Capital Pairs:")
for country, city in capitals.items():
    print(f"  The capital of {country} is {city}.")

Output:

Countries:
  France
  Japan
  Brazil

Capitals:
  Paris
  Tokyo
  Brasília

Country and Capital Pairs:
  The capital of France is Paris.
  The capital of Japan is Tokyo.
  The capital of Brazil is Brasília.

6. What Can Be a Dictionary Key? (Hashability)

In Python, dictionary keys must be hashable:

  • Allowed as keys: Strings, integers, floats, booleans, and tuples containing only hashable items.
  • NOT allowed as keys: lists, other dictionaries, or sets.
# Valid dictionary keys:
valid_dict = {
    "user_id": 101,             # String key
    42: "The Answer",           # Integer key
    (37.77, -122.41): "San Francisco" # Tuple key (coordinates)
}

# Invalid: Lists cannot be dictionary keys!
# bad_dict = {[1, 2]: "numbers"}  # TypeError: unhashable type: 'list'

Values, on the other hand, have no restrictions whatsoever. A value can be a string, a number, a list, another dictionary, or even a class instance.


7. Modern Dictionary Merging (Python 3.9+)

In Python 3.9+, you can merge dictionaries cleanly using the union operator (|):

default_settings = {"theme": "light", "notifications": True, "volume": 50}
user_overrides = {"theme": "dark", "volume": 75}

# Merge: user_overrides takes precedence for overlapping keys
active_config = default_settings | user_overrides

print(active_config)

Output:

{'theme': 'dark', 'notifications': True, 'volume': 75}

You can also update an existing dictionary in place using |=:

default_settings |= user_overrides

8. How Dictionaries Work: Hash Table Architecture

Why are dictionaries so beloved in Python? Speed.

In a list with 1,000,000 items, finding an element with target in my_list can take up to 1,000,000 comparisons (linear time, $O(n)$).

In a dictionary with 1,000,000 items, looking up my_dict[key] takes 1 step ($O(1)$ constant time)!

Key: "user_name" 
      │
      ▼
 hash("user_name") ──► 628913910398 ──► Bucket Index: 4 ──► Value: "Alice"
  1. Python passes the key to its internal hash() function.
  2. The hash produces a pseudo-random integer.
  3. Python maps that integer directly to an internal bucket index in memory.
  4. It fetches the value instantly without checking any other keys!

Summary & What’s Next

  • Dictionaries store data as {key: value} pairs.
  • Access values using dict[key] or safely with dict.get(key, default).
  • Keys must be immutable and hashable (strings, numbers, tuples); values can be anything.
  • Iterate over both keys and values using for k, v in dict.items():.
  • Dictionary lookups are blazingly fast ($O(1)$ constant time) thanks to hash tables.

What if you want the high-speed hash-table lookup of a dictionary, but only care about unique values without any keys? That brings us to sets.

Test your understanding of Python Dictionaries and Hash Maps

Quick interactive practice questions with instant feedback.

Take Quiz →