Python Dict

Beginner
9 min read
Updated: Nov 2026
3 examples
Key/value mappings

Definition and Usage

A dict (dictionary) stores key/value pairs: each unique key maps to one value, like a name to a phone number. You read a value with its key, phone["Asha"], instead of a position, and the lookup stays fast however big the dict grows.

A dict is mutable and insertion-ordered. The Dict Methods index lists every guide, such as get(), update(), and items().

Python Syntax

Curly braces hold key: value pairs separated by commas; square brackets read and write single keys:

Python
person = {"name": "Ada", "born": 1815}  # a dict literal
person["field"] = "math"                 # add a new key
print(person["name"])                    # Ada
print(person.get("died", "unknown"))     # unknown
print(len(person), "born" in person)     # 3 True
for key, value in person.items():
    print(key, "=", value)
Empty braces make a dict.

{} is an empty dict, not an empty set; write set() for an empty set. type({}) is dict.

Keys, Values, and Order

RuleWhat it means
Hashable keysKeys must be hashable: str, int, float, bool, None, frozenset, and tuples of hashable values. A list, dict, or set key raises TypeError: unhashable type.
Unique keysAssigning to an existing key replaces its value. Equal keys are the same key, so {1: "a", True: "b"} is {1: 'b'} because True == 1.
Insertion orderSince Python 3.7 the language guarantees that a dict remembers insertion order. Printing and looping follow that order.
Updating keeps positionAssigning a new value to an existing key keeps its place. Deleting a key and adding it again puts it at the end.
Any valuesValues can be anything, including lists and other dicts, and they do not have to be unique.
MutableA dict changes in place. Two names bound to the same dict see the same changes; use copy() for a separate dict.

Creating Dicts

CodeWhen to use it
{"a": 1, "b": 2}Literal: the most common way.
dict(a=1, b=2)Keyword arguments: keys become strings.
dict(zip(keys, values))Pair up two parallel lists.
{n: n * n for n in nums}Dict comprehension: compute keys and values.
dict.fromkeys(keys, 0)Same starting value for every key.

The dict() constructor also copies another mapping, and zip() pairs keys with values. fromkeys() has its own guide.

Looping Over a Dict

LoopWhat you get
for key in d:Keys, in insertion order (same as d.keys()).
for value in d.values():Values only.
for key, value in d.items():Both at once, unpacked from each pair.
for key in sorted(d):Keys in sorted order; the dict itself is unchanged.
for key in reversed(d):Keys from newest to oldest (Python 3.8+).

keys(), values(), and items() return live views, not copies, so they always show the current contents.

Common Mistakes

MistakeDo this instead
d["missing"] raises KeyErrorUse d.get(key, default), test key in d first, or catch KeyError.
Adding or deleting keys inside for key in d:Raises RuntimeError: dictionary changed size during iteration. Loop over list(d) or d.copy() instead. Changing values of existing keys is fine.
dict.fromkeys(keys, [])Every key shares one list. Use {k: [] for k in keys} for separate lists.
Using a list as a keyRaises TypeError: unhashable type: 'list'. Convert it to a tuple first.
new = old to copyBoth names point to one dict. Use old.copy(), or copy.deepcopy(old) for nested data.
settings = settings.update(x)update() returns None, so this throws the dict away. Call it on its own line.

Dict vs List vs Set

TypeLiteralBest forContentsOrder
dict{"a": 1}Look up by keyUnique, hashable keysInsertion order
list[1, 2, 1]Look up by positionDuplicates allowedPosition order
set{1, 2}Membership testsUnique, hashable itemsNo guaranteed order

Python Examples

Fixed data only, so the output is the same on every machine.

Example 1 — Create Dicts Four Different Ways

A literal, keyword arguments, two zipped lists, and a comprehension.

Python
literal = {"red": "#f00", "green": "#0f0"}
from_kwargs = dict(width=800, height=600)
from_pairs = dict(zip(["x", "y", "z"], [1, 2, 3]))
squares = {n: n * n for n in range(1, 5)}

print(literal)
print(from_kwargs)
print(from_pairs)
print(squares)

How It Works

  1. Literal braces. key: value pairs inside {} are the most direct way to write a dict.
  2. Keyword arguments. dict() turns width=800 into the string key 'width'.
  3. Two lists to one dict. zip() pairs each letter with a number and dict() turns the pairs into entries.
  4. Computed entries. The comprehension maps each number from 1 to 4 to its square; integer keys print without quotes.

Example 2 — See Insertion Order While Updating a Leaderboard

Update one score, delete and re-add a player, then loop with a rank number.

Python
scores = {"Kim": 12, "Lou": 7, "Max": 9}
scores["Lou"] = 15
del scores["Kim"]
scores["Kim"] = 3

for rank, (name, points) in enumerate(scores.items(), start=1):
    print(rank, name, points)
print(list(scores), sum(scores.values()))

How It Works

  1. Update in place. Lou's score changes from 7 to 15 without moving Lou.
  2. Delete and re-add. Kim is removed and inserted again, so Kim now comes last.
  3. Numbered loop. enumerate() adds a rank starting at 1, and the inner parentheses unpack each (name, points) pair.
  4. Keys and a total. list(scores) gives the keys in order and summing the values gives 15 + 9 + 3 = 27.

Example 3 — Hit the Classic Key Errors on Purpose

Tuple keys work, list keys fail, missing keys raise, and equal numbers collide.

Python
grid = {(0, 0): "start", (2, 3): "goal"}
print(grid[(2, 3)])

try:
    grid[[1, 1]] = "wall"
except TypeError:
    print("lists are unhashable and cannot be keys")

try:
    print(grid[(9, 9)])
except KeyError:
    print("missing key -> KeyError")

mixed = {1: "one", True: "true", 1.0: "float"}
print(mixed)

How It Works

  1. Tuples as keys. A tuple of numbers is hashable, so grid coordinates make good keys.
  2. Lists are rejected. A list can change, so it has no hash and using it as a key raises TypeError.
  3. Missing coordinates. Square brackets on a key that is not there raise KeyError.
  4. Equal keys collide. 1, True, and 1.0 are equal with the same hash(), so they are one key: the first key object stays and the last value wins.

Next: Python Dict Methods by Group

GroupMethods
Read keys, values, and itemsget(), keys(), values(), items()
Add and update entriesupdate(), setdefault(), fromkeys()
Remove entriespop(), popitem(), clear()
Copy a dictcopy()

Frequently Asked Questions

A dict is a built-in, mutable mapping from unique keys to values, such as {"name": "Ada", "born": 1815}. You look values up by key instead of by position.
Yes. Since Python 3.7 the language guarantees insertion order: printing and looping show keys in the order they were first added. Changing a value keeps the position.
Any hashable value: strings, numbers, booleans, None, frozensets, and tuples that contain only hashable values. Lists, dicts, and sets cannot be keys.
Use d.get(key) or d.get(key, default) for a fallback, check key in d before reading, use setdefault() to insert a default, or catch KeyError with try/except.
Use a dict when you look things up by a name or ID, such as a phone number by person. Use a list when order and position matter and items have no natural key.

Browse every dict method

Open the method index for categorized guides with examples and FAQs.

Dict Methods Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful