Learn by reading through in order

How to Use Python Dictionaries (dict)

Learn how the Python dict type stores key-value pairs and how to add, update, and look up entries safely in your browser.

Creating a dictionary

A dictionary (dict) is a type that stores values as key-value pairs.

Where a list is a box you pull values from by position (0, 1, 2…), a dict is a box you pull values from by name (key) — that's the easiest mental model.

Structure of a dictionary
"brand""Toyota""model""Prius""year"2015maps tomaps tomaps to

Wrap with { } and list key: value pairs separated by commas.

The key is the name, the value is the contents. Keys must be unique.

# Declare a dictionary
car = {
    "brand": "Toyota",
    "model": "Prius",
    "year": 2015,
}

print(car)            # {'brand': 'Toyota', 'model': 'Prius', 'year': 2015}
print(type(car))      # <class 'dict'>

# Keys don't have to be strings (numbers work too)
score_by_id = {1: 80, 2: 95, 3: 72}
print(score_by_id[2]) # 95

When to use list vs dict

If order or position matters, use list. If you want to look up by name, use dict.

For example, 'a ranking of 3 scores' is a list; 'scores per user' is a dict.

Even for the same data, how you want to retrieve it decides which one to pick.

Let's manage a user profile with a dictionary.

① Create a user dict with these 3 key-value pairs:

- "name": "Alice"

- "age": 28

- "email": "alice@example.com"

② Use user["name"] to print the name and user["age"] to print the age with print().

Python Editor

Run code to see output

Retrieving values — [] vs .get()

There are two ways to pull a value out of a dict, and the key difference is how they behave when the key doesn't exist.

How [] differs from .get()
car["color"](missing)[ ]KeyErrorraisedcar.get("color").get()Returns None(no error)lookupwhen missinglookupwhen missing

Try pulling a non-existent key out of the car dict with [] to see what happens.

① Print car["brand"] with print().

② Print car["color"] with print() and confirm that KeyError is raised.

Python Editor

Run code to see output

.get() lets you pass a default value as the second argument — that's the handy part.

You can say 'return this if the key isn't there' in a single line.

car = {"brand": "Toyota", "model": "Prius", "year": 2015}

# ① Access with []
print(car["brand"])        # Toyota
# print(car["color"])      # KeyError: 'color'

# ② Access with .get()
print(car.get("brand"))              # Toyota
print(car.get("color"))              # None
print(car.get("color", "Unknown"))  # Unknown (the second arg is returned)

.get() to keep running, [] to stay strict

If a missing key means something is broken, [] is safer — it surfaces the problem early as an error.

If it's fine either way (e.g., optional settings), passing a default to .get() reads better and cuts down on exception handling (covered later).

A user settings dict config = {"theme": "dark", "lang": "en"} is ready.

① Pull the current theme with config["theme"] and print it.

② Use .get() to fetch "font_size", falling back to 16 if it's not set.

Python Editor

Run code to see output

Add, update, delete

Dicts, like lists, can be modified after they're created.

The simplest way to add, update, and delete is direct assignment.

What to doSyntaxKey point
Add or updated["key"] = valueUpdates if the key exists, adds if not
Update multiple at onced.update(other_dict)Overwrites overlapping keys, adds new ones
Pop and deletev = d.pop("key")Deletes and stores the value. Missing key raises KeyError
Empty it outd.clear()The dict object stays, contents are emptied
Delete the variabledel dDeletes d itself. Later references raise an error
How d[key] = value behaves
car(no "color")car["color"]= "white"Addedcar(has "year")car["year"]= 2024Overwrittenassignmissing keyassignexisting key

The same syntax adds when the key is missing and updates when it's there.

The dict decides 'create if missing, overwrite if present' for you.

car = {"brand": "Toyota", "model": "Prius", "year": 2015}

# Add (new key)
car["color"] = "white"
print(car)
# {'brand': 'Toyota', 'model': 'Prius', 'year': 2015, 'color': 'white'}

# Update (existing key)
car["year"] = 2024
print(car["year"])   # 2024

# Update multiple at once
car.update({"country": "JP", "model": "Camry"})
print(car["model"])    # Camry (overwritten)
print(car["country"])  # JP (newly added)

# Pop and delete
old_year = car.pop("year")
print(old_year)        # 2024
# print(car["year"])   # KeyError (gone now)

# Empty it out
car.clear()
print(car)             # {}

Edit a user info dict.

user = {"name": "Alice", "age": 28} is ready.

① Update "age" to 29.

② Add "email": "alice@example.com" as a new entry.

③ Use update() to apply "country": "JP" and "age": 30 at once, then print the final user.

Python Editor

Run code to see output

Listing keys/values & checking existence

Last up: the tools for inspecting a dict.

There are 4 main ones — keys() / values() / items() / the in operator.

  • keys() — returns the list of keys (dict_keys(['brand', 'model', ...]))
  • values() — returns the list of values
  • items() — returns the list of key-value pairs (usually paired with a for loop)
  • "key" in dict — returns True / False depending on whether the key exists
The 4 tools at a glance
car.keys()key listcar.values()value listcar.items()pair list"key"in carTrue /False

Same dict, different calls depending on what you want to pull out.

keys / values / items return lists; in returns True / False.

car = {"brand": "Toyota", "model": "Prius", "year": 2015}

print(car.keys())     # dict_keys(['brand', 'model', 'year'])
print(car.values())   # dict_values(['Toyota', 'Prius', 2015])
print(car.items())    # dict_items([('brand', 'Toyota'), ...])

# Check for key existence (typically combined with if)
print("brand" in car)  # True
print("color" in car)  # False

if "brand" in car:
    print("Maker: " + car["brand"])
else:
    print("No maker info")

Combining for with items() (reference)

To iterate over a dict one item at a time, the standard form is for key, value in car.items():.

We'll cover for in a later chapter, so we won't dive deep here — but remember just this: items() lets you pull the key and value out together.

From the stock list stock = {"apple": 5, "banana": 0, "grape": 12}, write code that checks whether a given fruit is stocked and lists the keys.

① Use in to check if "banana" is a key in stock and print the result.

② For target = "lemon", print "{fruit} in stock: {count}" if it exists, or "Not carried" otherwise (the if template is in the comments).

③ Use stock.keys() to grab just the keys, wrap it with list(), and print it (the list of fruit names).

Python Editor

Run code to see output

In this article you learned how to declare a dict, how [] and .get() differ when retrieving, how to add, update, and delete entries, and how to check key existence and list contents.

Dicts show up everywhere in real work — user info, settings, stock, summary results. Once you internalize the image of a box you look up by key, you'll feel right at home with the data processing that comes next.

QUIZ

Knowledge Check

Answer each question one by one.

Q1For d = {"a": 1, "b": 2}, which one doesn't raise an error when you look up a missing key?

Q2After running d["a"] = 2 on d = {"a": 1}, what is d?

Q3Which method returns the list of keys?