Menu
Try in Playground

Python Dictionaries: Create, Access, Update, and Iterate dict

Dictionaries are Python's key-value lookup structure — the one data type you'll reach for constantly once you're past the basics.

A Dictionary Is a Lookup Table

Lists are indexed by position. Dictionaries are indexed by key — usually a string or a number — and each key maps to a value. That one shift unlocks a huge category of programs: inventories, configs, JSON payloads, user profiles, caches.

main.py
Output
Click Run to see the output here.

The keys and values can be almost anything. Keys need to be hashable (so: numbers, strings, tuples; not lists or other dicts). Values have no restriction — a dict can hold anything, including other dicts or lists.

Creating Dictionaries

Several ways, each with a place:

main.py
Output
Click Run to see the output here.

Reading Values

Two ways, and the choice matters:

main.py
Output
Click Run to see the output here.

Pick by intent:

  • Use [] when the key must be there. If it isn't, that's a bug and you want the loud error.
  • Use .get() when "not present" is a valid case. It lets you write defaults without try/except.

Adding, Updating, Deleting

Assigning to a key either creates or updates it:

main.py
Output
Click Run to see the output here.

update() merges another dict or iterable of pairs:

main.py
Output
Click Run to see the output here.

Shared keys in overrides overwrite the ones in settings.

Checking for a Key

in checks the keys, not the values:

main.py
Output
Click Run to see the output here.

To check values specifically, use user.values():

main.py
Output
Click Run to see the output here.

How to Iterate a Dictionary

You have three views you can loop over:

main.py
Output
Click Run to see the output here.

.items() is what you reach for most of the time — it gives you the pair, unpacked, ready to use.

Iteration order in modern Python (3.7+) matches insertion order. A dict is not a "magic bag" — if you add a then b then c, iterating yields them in that order. That's a language guarantee you can rely on.

How to Sort a Dictionary

Dictionaries preserve insertion order, so "sorting" a dict really means building a new dict whose keys are inserted in the order you want:

main.py
Output
Click Run to see the output here.

sorted() returns a list of pairs; wrapping that in dict(...) reconstructs a dictionary with the new order. If you only need the sorted pairs (not a dict), skip the outer dict() call.

How to Merge Two Dictionaries

Python 3.9+ gives you the | operator:

main.py
Output
Click Run to see the output here.

Values from the right-hand dict win on key collisions. .update() is the in-place equivalent. On older Python versions, use {**defaults, **overrides}.

The setdefault Pattern

A common need: "if the key is there, use its value; if not, set a default and then use it."

main.py
Output
Click Run to see the output here.

Or, better, use collections.Counter:

main.py
Output
Click Run to see the output here.

Counter is a dict subclass that does counting by default. It's the right call whenever you're counting occurrences.

Dictionary Comprehensions

Parallel to list comprehensions, but for building dicts:

main.py
Output
Click Run to see the output here.

Same rules as list comprehensions, but with key: value between the braces.

Dict as JSON's Twin

Python dicts line up almost exactly with JSON objects. Converting between them is a single call:

main.py
Output
Click Run to see the output here.

This is why dicts show up everywhere in web work — your API requests and responses are basically dict manipulation with some network in the middle.

A Practical Example

A tiny config-like program that tracks a user profile:

main.py
Output
Click Run to see the output here.

Nested dicts, mutable values, .get() with a default — the basic toolkit for any record-shaped data.

Moving On

Lists, tuples, sets, dicts. With those four collections in hand, you can model almost any data you'll encounter early on. Next, we'll learn the list comprehension — Python's compact way to transform one collection into another.

Frequently Asked Questions

What is a dictionary in Python?

A dictionary is a collection of key-value pairs. You look up a value by its key — prices['apple'] instead of prices[0]. Dictionaries are fast to read and write, keys must be unique, and in modern Python they preserve the order you inserted items in.

How do I add a key to a Python dictionary?

Assign to it: my_dict['new_key'] = 'new value'. If the key already exists, the value is overwritten. If it doesn't, it's added. There's no distinction between "insert" and "update" — it's the same syntax.

What's the difference between dict[key] and dict.get(key)?

dict[key] raises KeyError if the key isn't there. dict.get(key) returns None (or a default you provide) instead. Use .get() when missing keys are expected and normal; use [key] when a missing key is a bug.

Learn to code with Coddy

GET STARTED