Python Dictionary Explained

Learn Python dictionary with simple examples, including dictionary syntax, creating dictionaries, accessing values, adding and updating items, looping, checking keys, removing items, and common dictionary methods.

Published

Updated

Read time 7 min read

Reviewed byDeepak Prasad

Python Dictionary Explained

This guide walks you through Python dictionaries in the order you usually need them: syntax, creating dicts, reading and updating values, looping, membership checks, removal, copying, and a compact methods table.

python
student = {
    "name": "Alice",
    "age": 21,
    "course": "Python",
}

print(student)
Output

A dictionary stores data as key-value pairs inside curly braces {}. Each key maps to one value, and you look up values by key—not by numeric index like a Python list. In modern Python, dicts preserve insertion order when you iterate or print them, while the tutorial still stresses that lookups are keyed, not positional.

When you pass a plain dict to any() or all(), Python walks the keys; see Python any() and all() if you use those helpers on mappings. For adding keys in depth, see Python add to dictionary; for nested trees, see nested dictionary in Python; for merging dicts, see extend dictionary and merge dictionaries.

Tested on: Python 3.13.3; kernel 6.14.0-37-generic.


What is a dictionary in Python?

A dictionary (dict) is a mutable mapping: a collection of keys, each associated with a value. Keys in one dict are unique; assigning again overwrites the previous value. Values can be any Python object, including lists or other dicts.

Before Python 3.7, people sometimes used collections.OrderedDict when insertion order mattered; today the built-in dict also keeps insertion order, so beginners can rely on normal dict unless a library specifically requires OrderedDict.


Python dictionary syntax

  • Literals use curly braces {}, with key: value pairs separated by commas.
  • Keys must be hashable (strings, numbers, tuples of immutables, etc.); values can be anything.
  • Keys are unique: {"a": 1, "a": 2} ends up as {"a": 2}.
  • The constructor dict(...) does not use key: value inside the parentheses; use dict(name=value, ...) for string keys that are valid identifiers, or pass a list of pairs (see below).

Create a dictionary in Python

Use braces and string keys for a readable record:

python
cars = {
    "hyundai": "i10",
    "maruti": "swift",
    "honda": "city",
}
print(cars["maruti"])
Output

You should see swift.


Create an empty dictionary

Two common spellings:

python
a = {}
b = dict()
print(type(a), len(a), len(b))
Output

Both create an empty dict. Use {} for an empty dict; set() is the empty set, not {}.


Create a dictionary using dict()

Keyword arguments become string keys (identifiers only). For arbitrary keys, pass an iterable of (key, value) pairs:

python
cars = dict(hyundai="i10", maruti="swift", honda="city")
also = dict([("hyundai", "i10"), ("maruti", "swift"), ("honda", "city")])
print(cars == also)
Output

You should see True. You cannot write dict(hyundai: "i10")—colons belong in {} literals, not in the dict() call.


Access dictionary values using keys

Use square brackets. If the key is missing, Python raises KeyError.

python
user = {"name": "Ada", "score": 100}
print(user["name"])
Output

You should see Ada.


Access values safely using get()

dict.get(key, default) returns the value if the key exists, otherwise None or your default—no exception.

python
cfg = {"host": "localhost"}
print(cfg.get("port"))
print(cfg.get("port", 8080))
Output

You should see None on the first line and 8080 on the second.


Add item to a dictionary

Assign to a new key:

python
user = {"name": "Bob"}
user["city"] = "Delhi"
print(user)
Output

You should see city in the printed dict.


Update item in a dictionary

Assign to an existing key to replace its value:

python
user = {"name": "Bob", "age": 20}
user["age"] = 21
print(user["age"])
Output

You should see 21.


Add or update multiple items using update()

update() merges another mapping or iterable of pairs into the dict in place. Existing keys get new values from the right-hand data.

python
user = {"name": "Kim", "age": 30}
user.update({"age": 31, "city": "Seoul"})
print(user)
Output

You should see age updated and city added. This is map-style growth, not the same as list.append or list.extend.


Check if a key exists in dictionary

Use in or not in:

python
user = {"name": "Lee"}
print("name" in user, "age" in user)
Output

You should see True then False.


Loop through a dictionary

Loop through keys

Calling keys() is optional; iterating the dict iterates keys by default.

python
scores = {"ada": 10, "bob": 20}
for name in scores:
    print(name)
Output

You should see ada and bob on separate lines in insertion order.

Loop through values

python
scores = {"ada": 10, "bob": 20}
for value in scores.values():
    print(value)
Output

You should see 10 then 20.

Loop through keys and values

python
scores = {"ada": 10, "bob": 20}
for name, value in scores.items():
    print(name, value)
Output

You should see two lines pairing each name with its score.


Remove item from a dictionary

Remove item using del

del d[key] drops a key; missing keys raise KeyError.

python
d = {"a": 1, "b": 2}
del d["a"]
print(d)
Output

You should see only b.

Remove item using pop()

pop(key) removes the key and returns its value; you can pass a default to avoid errors when the key is missing.

python
d = {"a": 1, "b": 2}
print(d.pop("a"), d.pop("z", None))
print(d)
Output

You should see 1, None, then {'b': 2}.

Remove last item using popitem()

In Python 3.7 and newer, popitem() removes and returns the last inserted (key, value) pair as a tuple (not a random pair).

python
d = {"x": 1}
d["y"] = 2
print(d.popitem())
print(d)
Output

You should see ('y', 2) removed last, then the dict with only x.


Clear all items from a dictionary

clear() removes every key-value pair; the object stays the same dict instance.

python
d = {"a": 1}
d.clear()
print(d, len(d))
Output

You should see {} and length 0.


Copy a dictionary

copy() makes a shallow copy: the outer dict is new, but values that are mutable objects are shared with the original.

python
inner = [1, 2]
a = {"k": inner}
b = a.copy()
b["k"].append(3)
print(a["k"], b["k"])
Output

Both lists show [1, 2, 3]. For a fully independent nested structure, use copy.deepcopy from the copy module.


Common Python dictionary methods

Method Use
dict.get(key) Get value without raising on missing key
dict.keys() View of keys
dict.values() View of values
dict.items() View of (key, value) pairs
dict.update(other) Add or overwrite many keys in place
dict.pop(key) Remove key and return its value
dict.popitem() Remove and return last inserted pair (3.7+)
dict.clear() Remove all items
dict.copy() Shallow copy of the dict
dict.setdefault(key, default) Return value if key exists, else set default and return it

setdefault is handy when building tallies or caches. To present keys in sorted order, see sort dictionary by key or sort dictionary by value.

python
counts = {}
for ch in "aba":
    counts[ch] = counts.setdefault(ch, 0) + 1
print(counts)
Output

You should see {'a': 2, 'b': 1}.


Common mistakes with Python dictionaries

  • Using () instead of {} for a dict literal—you get a tuple, not a mapping.
  • Writing dict(hyundai: "i10") with colon syntax; use dict(hyundai="i10") or pairs like [("hyundai", "i10"), ...].
  • Using d[key] when the key might be missing; you get KeyError unless you guard with in or use get.
  • Expecting duplicate keys to keep two values—the last one wins.
  • Treating dicts like lists: d[0] is not the “first value” unless the key is actually 0.
  • Believing popitem() is random on current Python; it pops the last inserted item in the usual case.
  • Confusing update() with append/extend on lists; dicts merge by key, not by position.
  • Using mutable values (like lists) as keys; keys must be hashable.

To confirm an object is a dict, type(x) is dict or isinstance(x, dict) is enough for most scripts—no need for a long sidebar on typing here.


Python dictionary quick reference table

Need Example
Create dictionary user = {"name": "Alice", "age": 21}
Create empty dictionary user = {}
Create using dict() user = dict(name="Alice", age=21)
Access value user["name"]
Access safely user.get("name")
Add item user["city"] = "Delhi"
Update item user["age"] = 22
Add many items user.update({"city": "Delhi"})
Check key "name" in user
Loop items for key, value in user.items():
Remove item user.pop("age")
Clear dictionary user.clear()

Summary

Dictionaries map unique keys to values with {} syntax or the dict() constructor. You read with [] or get, write with assignment or update, loop with .items(), test membership with in, and remove with del, pop, or popitem(). Modern dicts keep insertion order; use keys for access, not list-style positions. For shallow copies use copy(); reach for deepcopy when nested mutables must diverge. Compare containers in list vs set vs tuple vs dictionary.


References


Frequently Asked Questions

1. How is a Python dictionary different from a list?

A list orders values by integer index; a dict maps keys (often strings) to values, looks up by key in constant average time, and preserves insertion order in modern Python—use keys, not positions 0, 1, 2.

2. What happens if I use the same key twice in one dict literal?

Later entries win; the dictionary never stores two values under one identical key.

3. When should I use get() instead of square brackets?

Use get() when a missing key is normal and you want None or a default without catching KeyError; use d[key] when the key must exist or you want an exception if it does not.

4. Does popitem() remove a random key?

In Python 3.7+ (including current CPython), popitem() removes the last inserted key-value pair in the usual case; it is not random.

5. Can I use a list as a dictionary key?

No—keys must be hashable and immutable; lists are mutable, so use a tuple (if its contents are hashable) or convert to a string, or use dicts nested under hashable keys.
Deepak Prasad

R&D Engineer

Founder of GoLinuxCloud with more than 15 years of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive …