Skip to content
Foxipa

Suggest an edit

Tell us what should be corrected, clarified, or improved. Submission will be connected to Foxipa’s contribution service later.

No information is sent anywhere yet. Your suggestion is only prepared in your browser.

Learning

Python Dictionaries

Learn the labeled container: storing values under keys, safe lookup with get, adding and removing entries, and walking keys, values, and pairs.

Levels: Beginner ~14 min read

Basic

A list answers the question what comes next. A dictionary answers the question what is the value for this label. Written in braces as pairs of key: value , it stores each value under a key you choose, a string, a number, a tuple, and hands it back the instant you present that key. Nearly every real program eventually holds data whose natural shape is name-and-value rather than position, and this is the container built for it.

Storing and fetching

python basics.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
loaf = {
    "name": "sourdough",
    "weight": 500,        # grams
    "price": 45.5,
    "vegan": True,
}

loaf["name"]     # "sourdough"
loaf["weight"]   # 500
loaf["price"]    # 45.5

Curly braces, colon pairs, and lookup by name.

Fetching with a missing key raises a KeyError, which is loud and immediate. When absence is an expected state rather than a bug, loaf.get("discount") returns None quietly, and loaf.get("discount", 0) returns a default you choose instead. The choice between brackets and get is the choice between missing-as-mistake and missing-is-fine, and making it consciously is most of using dictionaries well.

Changing what is stored

Dictionaries are mutable like lists: assignment writes through. Assigning to an existing key replaces its value, assigning to a new key creates the entry on the spot, and del removes a pair entirely. The in operator asks about keys, not values, which is worth saying aloud once: "price" in loaf is a question about labels.

python mutating.py
1
2
3
4
5
6
7
stock = {"sourdough": 12, "rye": 4}

stock["rye"] = 2            # update an entry
stock["flatbread"] = 8      # create a new one
del stock["rye"]          # remove a pair

print(stock)   # {'sourdough': 12, 'flatbread': 8}

Write, create, and delete, all through the key.

Walking the contents

A for loop over a dictionary walks its keys by default. The three views, keys(), values(), and items(), let you choose what you actually want, and items() with tuple unpacking is the idiom that makes dictionaries a pleasure to read.

python views.py
1
2
3
4
5
6
7
8
for name in stock:                # keys
    print(name)

for count in stock.values():      # values
    print(count)

for name, count in stock.items(): # pairs
    print(f"{name}: {count}")

Three views, and the one you will actually use.

Nesting: dictionaries of dictionaries

Values can be anything, including lists and other dictionaries, and that is how real records are built: a dictionary per loaf, a list of them for the menu, keys for the fields. Chained brackets reach in, menu[0]["price"], and a loop over the list with items() inside composes the two containers naturally. Start simple, one level at a time, and print as you go; nested data forgives everything except silence.

Run the bakery board

The example below keeps a menu in one dictionary and a day's orders in another, then reports on both. Run it, then exercise the edges: ask for a missing bread with brackets to meet the KeyError in person, then switch to get with a default and watch the program survive. Add a new bread to the menu mid-file and watch every later report pick it up without ceremony.

Interactive Runnable example
Edit

Ready to run.

What to notice

  • The orders loop looked prices up in the other dictionary by key; the two containers worked as a pair without any index math.

  • Missing keys were handled twice, once with a default and once by construction, because every ordered bread existed in the menu.

  • Dictionary order matched the order entries were written and added, which Python has guaranteed since version 3.7.


Quick check

If you can choose between brackets and get with a reason, iterate pairs with items() without hesitating, and explain what in asks a dictionary, labeled data is yours. Next, loops does the walking for everything so far. When you are ready, take the Python Dictionaries quiz.

Was this page helpful?

Mark this learning resource complete to track your learning progress.