Skip to content

Python Dictionaries

Updated 6 min read Aimerscrew

A list is great when items are numbered: first, second, third. But often you want to find data by a name, not a number. Python dictionaries let you do exactly that by storing key-value pairs. In this lesson, you'll learn how to create dictionaries, read, add, change and delete values, loop through them, and nest them.

🌍 Real-life example

Your phone's contacts list is a dictionary. You don't remember that Mom is "contact number 37"; you search for the name Mom (the key) and get her phone number (the value). Each name points to exactly one entry.

What is a dictionary in Python?

A dictionary (type dict) is a collection of key-value pairs. The key is the label you search by, and the value is the data attached to it. You write a dictionary with curly braces, a colon between each key and its value, and commas between pairs:

contacts = {
    "Mom": "+1 555 0100",
    "Alex": "+44 20 7946 0018",
    "Pizza place": "+1 555 0199",
}

print(contacts["Alex"])
print(len(contacts))
+44 20 7946 0018
3

len() counts the pairs, not the individual keys and values.

A dictionary named product with three keys, name, price and in_stock, each with an arrow pointing to its value: Desk lamp, 24.99 and True. Looking up product['price'] follows the price arrow to 24.99
Each key points to one value. You find a value by its key, not by its position.

How do you create a dictionary?

Besides curly braces, you can use the built-in dict() function with key=value arguments. An empty pair of braces makes an empty dictionary:

product = {"name": "Desk lamp", "price": 24.99, "in_stock": True}
settings = dict(theme="dark", volume=7)
cart = {}

print(product)
print(settings)
print(cart)
{'name': 'Desk lamp', 'price': 24.99, 'in_stock': True}
{'theme': 'dark', 'volume': 7}
{}

Values can be any type: strings, numbers, booleans, lists, even other dictionaries.

Accessing values: [] vs get()

There are two ways to read a value. Square brackets are short, but they raise a KeyError if the key doesn't exist:

profile = {"username": "skyrunner", "country": "Canada"}
print(profile["username"])
print(profile["email"])
skyrunner
KeyError: 'email'

The get() method is the safe option. It returns None for a missing key, or a default value that you choose:

profile = {"username": "skyrunner", "country": "Canada"}
print(profile.get("country"))
print(profile.get("email"))
print(profile.get("email", "not provided"))
Canada
None
not provided

💡 Tip

Use [] when the key must be there (a missing key is a bug you want to see). Use get() when the key is optional, like data a user may or may not have filled in.

Adding and updating items

Assigning to a key does double duty: if the key is new, the pair is added; if it already exists, its value is replaced. That's because keys are unique.

stock = {"apples": 12, "bananas": 6}

stock["cherries"] = 30   # new key: added
stock["apples"] = 10     # existing key: updated
stock["bananas"] += 4    # change using the current value

print(stock)
{'apples': 10, 'bananas': 10, 'cherries': 30}

To change several pairs at once, use update(). You'll see it and many more in Python dictionary methods.

Deleting items: del and pop()

del removes a pair by key. pop() removes it and gives you the value back, which is handy when you still need it:

order = {"burger": 8.5, "fries": 3.0, "soda": 2.0}

del order["soda"]
removed_price = order.pop("fries")

print(order)
print("Refund:", removed_price)
{'burger': 8.5}
Refund: 3.0

Both raise a KeyError if the key isn't there, unless you give pop() a default, like order.pop("salad", 0).

How do you loop through a dictionary?

A plain for loop over a dictionary gives you its keys. Use values() for the values, and items() for both at once:

scores = {"Lina": 88, "Omar": 95, "Kate": 79}

for name in scores:
    print(name)

for points in scores.values():
    print(points)

for name, points in scores.items():
    print(f"{name} scored {points}")
Lina
Omar
Kate
88
95
79
Lina scored 88
Omar scored 95
Kate scored 79

items() hands back each pair as a tuple, and name, points unpacks it into two variables, the same way you unpacked tuples.

📝 Dictionaries keep insertion order

Since Python 3.7, dictionaries remember the order in which keys were added, and loops follow that order. Updating an existing key keeps its original spot.

Checking whether a key exists

The in operator checks keys, not values. Like sets, dictionaries use hashing, so this check is very fast even for huge dictionaries.

capitals = {"France": "Paris", "Japan": "Tokyo"}
print("Japan" in capitals)
print("Tokyo" in capitals)
print("Tokyo" in capitals.values())
True
False
True

Nested dictionaries

A value can be another dictionary. This is perfect for records with several fields, like a product catalog. Chain the keys to dig in:

catalog = {
    "SKU101": {"name": "Running shoes", "price": 79.99, "sizes": [8, 9, 10]},
    "SKU102": {"name": "Water bottle", "price": 12.50, "sizes": []},
}

print(catalog["SKU101"]["name"])
print(catalog["SKU101"]["sizes"][-1])

for sku, info in catalog.items():
    print(f"{sku}: {info['name']} costs ${info['price']}")
Running shoes
10
SKU101: Running shoes costs $79.99
SKU102: Water bottle costs $12.5

Notice the f-string uses single quotes inside (info['name']) because the string itself uses double quotes. See f-strings for more.

What can be a dictionary key?

Keys must be immutable (unchangeable), such as strings, numbers, booleans or tuples. Lists can't be keys because they can change:

flights = {("JFK", "LHR"): "7h 05m"}   # a tuple key works
print(flights[("JFK", "LHR")])

routes = {["JFK", "LHR"]: "7h 05m"}
7h 05m
TypeError: unhashable type: 'list'

Values have no such rule. A value can be anything, including a list.

Real-world example: a user profile

user = {
    "name": "Priya",
    "plan": "free",
    "playlists": ["Workout", "Chill"],
}

user["plan"] = "premium"
user["playlists"].append("Road trip")
user["verified"] = True

print(f"{user['name']} is on the {user['plan']} plan")
print("Playlists:", len(user["playlists"]))
print("Verified:", user.get("verified", False))
Priya is on the premium plan
Playlists: 3
Verified: True

Common mistakes with dictionaries

1. Reading a key that doesn't exist

profile["email"] crashes with KeyError when the key is missing. Use profile.get("email") or check with in first.

2. Expecting duplicate keys to both be kept

prices = {"tea": 2.5, "coffee": 3.0, "tea": 2.75}
print(prices)
{'tea': 2.75, 'coffee': 3.0}

A key can appear only once. The last value wins.

3. Accessing by position

menu = {"pasta": 11, "salad": 8}
print(menu[0])
KeyError: 0

Square brackets take a key, not an index. Python looks for a key named 0 and doesn't find one.

Practice exercise

🏋️ Try it yourself

Create a dictionary for a weather report with keys city ("Sydney"), temp_c (24) and condition ("sunny"). Then change the temperature to 26, add a key humidity with 60, and loop through the dictionary to print every pair as key: value.

Show solution
weather = {"city": "Sydney", "temp_c": 24, "condition": "sunny"}

weather["temp_c"] = 26
weather["humidity"] = 60

for key, value in weather.items():
    print(f"{key}: {value}")
city: Sydney
temp_c: 26
condition: sunny
humidity: 60

What's next?

You now know how to build and use dictionaries. Next, explore the full toolbox in Python dictionary methods, including setdefault(), update(), fromkeys() and dictionary comprehensions.

Key takeaways

  • A dictionary stores key-value pairs, written like {"name": "Ava", "age": 30}.
  • Read values by key: d["key"] raises KeyError if missing, d.get("key", default) does not.
  • d["key"] = value adds a new pair or replaces the value of an existing key.
  • Remove pairs with del d["key"] or d.pop("key"), which also returns the value.
  • Loop over keys directly, over values with values(), and over pairs with items().
  • Keys must be unique and immutable (strings, numbers, tuples); values can be anything.
  • Dictionaries keep insertion order (Python 3.7+) and can be nested.

Frequently asked questions

What is a dictionary in Python?

A dictionary is a built-in collection of key-value pairs. You look up a value by its key, for example prices["coffee"], instead of by a numeric position.

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

d[key] raises a KeyError when the key does not exist. d.get(key) returns None instead, or a default you pass as the second argument, such as d.get(key, 0).

Are Python dictionaries ordered?

Yes. Since Python 3.7, dictionaries keep the order in which keys were inserted, and looping follows that order. They still cannot be accessed by index.

Can a Python dictionary have duplicate keys?

No. Keys are unique. If you assign the same key twice, the second value replaces the first.

Can a list be a dictionary key in Python?

No. Keys must be hashable, which means immutable. Use a tuple instead of a list if you need a key made of several values.

How do you loop through keys and values of a dictionary?

Use the items() method: for key, value in my_dict.items(): print(key, value). It gives each pair as a tuple that you unpack into two variables.