Python Dictionaries: Key-Value Storage, Lookup, and Common Uses

Python dictionaries store values by key, so you can find data quickly when you know the key. They are the standard way to model lookups, settings, counts, and records in Python. This article shows how dictionaries work, how to use them safely, and where beginners usually get tripped up.

Difficulty: Beginner

Helpful to know first: Basic Python syntax, variables, lists, and how functions return values.

How Python Dictionaries Store and Find Data

A dictionary is a collection of key and value pairs. You use the key to get the value, almost like looking up a word in a real dictionary. The key must be something immutable and hashable, such as a string, number, or tuple of immutable values.

The smallest useful dictionary looks like this:

Python
person = {"name": "Ada", "age": 36}

print(person["name"])
print(person["age"])
# Output:
# Ada
# 36

Here, "name" and "age" are the keys. The values are "Ada" and 36. Python uses the key to find the value directly, which is why dictionaries are so useful for fast lookups.

What makes a dictionary different from a list

A list uses numeric positions. A dictionary uses keys that you choose. That makes dictionaries better when the thing you want to find already has a meaningful label, such as a username, product ID, or country code.

Python
scores = {"Mina": 91, "Omar": 88}
print(scores["Mina"])
# Output: 91

A list would force you to remember that Mina is at index 0 or 1. A dictionary lets you use the name directly.

Creating, Reading, and Updating Dictionary Values

You can create a dictionary with braces or with the dict() constructor. Most code uses braces because they are shorter and clearer when you already know the keys.

Creating a dictionary literal

This is the most common form. Each key is followed by a colon, and pairs are separated by commas.

Python
profile = {
    "username": "sam123",
    "active": True,
    "logins": 5,
}

print(profile)
# Output: {'username': 'sam123', 'active': True, 'logins': 5}

Python displays dictionaries with curly braces. The order you type the items in is the order Python keeps when iterating, but the main job of a dictionary is still key-based lookup, not position.

Reading a value by key

Use square brackets to get a value by its key. If the key is missing, Python raises an error, which you will learn about later.

Python
settings = {"theme": "dark", "font_size": 14}

print(settings["theme"])
# Output: dark

Adding a new key or changing an existing one

Assignment works the same way for new keys and existing keys. If the key does not exist, Python creates it. If it already exists, Python replaces the old value.

Python
student = {"name": "Iris"}
student["grade"] = "A"
student["name"] = "Iris Chen"

print(student)
# Output: {'name': 'Iris Chen', 'grade': 'A'}

This is one of the easiest ways to build up a dictionary step by step.

Common Dictionary Methods You Will Use Most

Python dictionaries have a small set of methods that cover most daily tasks. These methods help you read values safely, iterate through data, and remove entries when needed.

Using get() to avoid KeyError

The get() method returns a value if the key exists. If the key is missing, it returns None by default, or a fallback value that you choose.

Python
user = {"name": "Nia"}

print(user.get("name"))
print(user.get("age"))
print(user.get("age", 0))
# Output:
# Nia
# None
# 0

Use get() when a missing key is normal and should not crash the program.

Using keys(), values(), and items()

These methods let you inspect the contents of a dictionary. keys() gives you the keys, values() gives you the values, and items() gives you key-value pairs.

Python
inventory = {"apple": 3, "banana": 5}

print(list(inventory.keys()))
print(list(inventory.values()))
print(list(inventory.items()))
# Output:
# ['apple', 'banana']
# [3, 5]
# [('apple', 3), ('banana', 5)]

These views are useful in loops and when you need to test whether a key or value exists.

Removing entries with pop() and del

Use pop() when you want the removed value back. Use del when you only want to delete the entry.

Python
cart = {"book": 2, "pen": 4}
removed = cart.pop("pen")
del cart["book"]

print(removed)
print(cart)
# Output:
# 4
# {}

After those two removals, the dictionary is empty.

How Dictionary Keys Behave in Python

The most important rule is that keys must be hashable. That means the object must have a stable hash value for its lifetime. Strings, integers, floats, booleans, and tuples of immutable values work. Lists and other mutable containers do not.

Why mutable objects cannot be keys

If a key could change after Python stored it, Python would no longer know where to find the value. That is why lists cannot be dictionary keys.

Python
bad = {[1, 2]: "pair"}
# TypeError: unhashable type: 'list'

The fix is to use an immutable type such as a tuple:

Python
good = {(1, 2): "pair"}
print(good[(1, 2)])
# Output: pair

This rule also explains why dictionary keys should be chosen carefully when the key is a custom object.

Why equal keys replace older values

If two keys compare as equal, Python keeps one entry and overwrites the old value. This can surprise beginners when they mix True, 1, and 1.0.

Python
data = {True: "yes", 1: "one", 1.0: "float"}

print(data)
print(len(data))
# Output:
# {True: 'float'}
# 1

In Python, those keys compare equal, so they refer to the same dictionary slot. This is a real-world edge case that matters in code that uses numeric identifiers or mixed boolean and numeric values.

Working with Dictionaries in Real Programs

Dictionaries are not just for toy examples. They are one of Python’s main tools for modeling structured data.

Counting things

A dictionary is a natural choice for counting how often each item appears. You start with an empty dictionary and increase a count each time you see a value.

Python
words = ["red", "blue", "red", "green", "blue", "red"]
counts = {}

for word in words:
    counts[word] = counts.get(word, 0) + 1

print(counts)
# Output: {'red': 3, 'blue': 2, 'green': 1}

This pattern is common because it is simple and does not require extra libraries.

Storing structured records

You can use a dictionary to represent one object with named fields. This is useful for simple records where a full class would be too much.

Python
book = {
    "title": "The Python Way",
    "author": "A. Reader",
    "pages": 240,
}

print(book["author"])
# Output: A. Reader

That style is common in JSON-like data and small scripts.

Building a lookup table

When you need to translate one value into another, a dictionary is often the best fit. The key is the input, and the value is the result you want back.

Python
caps = {"us": "Washington, D.C.", "fr": "Paris", "jp": "Tokyo"}

print(caps["fr"])
# Output: Paris

Without a dictionary, you would need a longer chain of if and elif statements.

How Dictionary Lookup and Mutation Work in Practice

Dictionaries are optimized for fast lookup by key. That is why they are used for membership tests, caches, and data that changes over time. The order of items is preserved when you iterate over a dictionary in modern Python, but that does not make it a list. You should not use index positions to access dictionary data.

Membership testing checks keys, not values. This matters because "name" in person asks whether the key exists, not whether the value contains that string.

Python
person = {"name": "Ada", "age": 36}

print("name" in person)
print("Ada" in person)
# Output:
# True
# False

To search values, use values() or another structure if repeated value lookups are common.

A dictionary is usually the right choice when you want named access, fast lookup, and flexible updates. If you need ordered positions, use a list instead.

Predict the Output

These small examples check the parts of dictionaries that beginners often misunderstand.

Using get() versus square brackets

What does this print?

Python
config = {"debug": False}

print(config.get("mode"))
print(config["debug"])
Show answer

The first call prints None because mode is missing and get() returns None by default. The second call prints False because the key exists.

Terminal
# Output:
# None
# False

Equal keys in one dictionary

What happens?

Python
data = {True: "yes", 1: "one"}

print(data)
print(len(data))
Show answer

Python stores only one entry because True and 1 compare as equal and have the same hash. The later value replaces the earlier one.

Terminal
# Output:
# {True: 'one'}
# 1

Common Mistakes with Python Dictionaries

Using a missing key with square brackets

Beginners often assume that a missing key behaves like an empty value. Square brackets do not do that. They raise an error immediately.

Problem: The code asks for a key that does not exist, so Python cannot return a value.

Python
user = {"name": "Lina"}
print(user["age"])
# KeyError: 'age'

Fix: Use get() if the key may be missing, or check membership first.

Python
user = {"name": "Lina"}
print(user.get("age", "unknown"))
# Output: unknown

The fixed version works because it supplies a default value when the key is absent.

Trying to use a list as a key

A list looks useful as a key when it groups values together, but lists are mutable and cannot be hashed.

Problem: Python rejects mutable objects as dictionary keys because they could change after insertion.

Python
lookup = {[1, 2]: "pair"}
# TypeError: unhashable type: 'list'

Fix: Use a tuple or another immutable type instead.

Python
lookup = {(1, 2): "pair"}
print(lookup[(1, 2)])
# Output: pair

The corrected version works because tuples do not change after they are created.

Assuming a dictionary is indexed by position

Some beginners try to read a dictionary by number, the way they would read a list. That does not work, because a dictionary has keys, not numeric positions.

Problem: The code uses a number as if the dictionary were a list, but the number is not a key.

Python
prices = {"apple": 2, "pear": 3}
print(prices[0])
# KeyError: 0

Fix: Use the actual key, or convert the keys to a list if you truly need positional access.

Python
prices = {"apple": 2, "pear": 3}
print(prices["apple"])
# Output: 2

The corrected version works because the key matches an actual dictionary entry.

Using a shared mutable default dictionary pattern by accident

When a dictionary is created outside a function and then reused, changes in one place can affect later calls. This is a common source of confusing bugs when people are trying to build fresh data each time.

Problem: The same dictionary object is reused, so updates from one call remain in later calls.

Python
cache = {}

def add_item(key, value):
    cache[key] = value
    return cache

print(add_item("a", 1))
print(add_item("b", 2))
# Output:
# {'a': 1}
# {'a': 1, 'b': 2}

Fix: Create a new dictionary inside the function when you want a fresh result each time.

Python
def add_item(key, value):
    result = {}
    result[key] = value
    return result

print(add_item("a", 1))
print(add_item("b", 2))
# Output:
# {'a': 1}
# {'b': 2}

The corrected version works because it builds a new dictionary for each call.

Find the Bug

The code below is meant to count how many times each letter appears. One line is wrong. Find it before looking at the answer.

Python
letters = ["a", "b", "a", "c"]
counts = {}

for letter in letters:
    if letter in counts:
        counts[letter] = 1
    else:
        counts[letter] = counts. get(letter, 0) + 1

print(counts)
Show answer

The bug is the reversed logic. When the letter is already in the dictionary, the code resets its count to 1 instead of increasing it. The else branch is also awkward because it only increments when the key is missing.

Fixed code:

Python
letters = ["a", "b", "a", "c"]
counts = {}

for letter in letters:
    counts[letter] = counts.get(letter, 0) + 1

print(counts)
# Output: {'a': 2, 'b': 1, 'c': 1}

The fixed version works because each pass reads the current count, adds one, and stores the new value back under the same key.

When to Use a Dictionary and When to Use Something Else

Use a dictionary when you need named access by key. Use another structure when you need ordering by position, repeated values without keys, or automatic counting of complex objects with a built-in helper.

Choose thisWhen it fitsExample strength
dictYou want fast lookup by a meaningful key.Settings, records, caches, lookup tables
listYou care about position or sequence.Ordered steps, queues, collections of items
setYou only care whether something is present.Unique membership, deduplication

A dictionary is not a replacement for every collection type. It is the best fit when the key is the thing you already know and the value is the thing you want.

Dictionary versus list in one sentence

If you access items by label, use a dictionary. If you access items by number or sequence order, use a list.

Dictionary versus set in one sentence

If you need to store values and look up matching data, use a dictionary. If you only need unique items and membership tests, use a set.

Interview Questions About Python Dictionaries

Why are dictionary keys required to be hashable?

Python uses the key’s hash to find where the value is stored. If the key could change, the hash could change too, and the dictionary would lose track of the entry. That is why mutable objects like lists cannot be keys.

What is the difference between d[key] and d.get(key)?

d[key] raises KeyError if the key is missing. d.get(key) returns None by default, or a default value you choose. Use brackets when the key must exist. Use get() when missing data is expected.

Can a dictionary store mixed value types?

Yes. A dictionary can store strings, numbers, lists, other dictionaries, or any other Python object as a value. The keys must still be hashable, but the values can be any type.

Try It Yourself

Build a dictionary from a list of product names and count how many times each product appears.

  • Start with the list ["tea", "coffee", "tea", "cake", "coffee", "tea"].
  • Create an empty dictionary called counts.
  • Loop through the list and update the count for each product.
  • Print the final dictionary.

Expected output: {'tea': 3, 'coffee': 2, 'cake': 1}

Hint: Use get() with a default of 0, then add 1.

Show solution
Python
products = ["tea", "coffee", "tea", "cake", "coffee", "tea"]
counts = {}

for product in products:
    counts[product] = counts.get(product, 0) + 1

print(counts)
# Output: {'tea': 3, 'coffee': 2, 'cake': 1}

Summary

  • Dictionaries store values by key, not by position.
  • Square brackets raise KeyError when a key is missing.
  • get() is safer when a missing key is normal.
  • Keys must be hashable, so lists cannot be dictionary keys.
  • Equal keys share one slot, so later assignments can replace earlier values.
  • Use dictionaries for lookup tables, records, and counts; use lists when order and position matter.

Next, study Python sets to see another collection type that uses hash-based storage but keeps only unique values.