☰

Python Dictionary

Python Dictionary Tutorial for Beginners

Open the contacts app on your phone. You do not scroll through numbers to find a person. You look up a name, and the phone gives you the number that belongs to it. A Python dictionary works the same way. It stores information as pairs, a name and its value, and lets you find any value instantly by asking for its name.

Dictionaries are one of the most useful data types in Python. They hold student records, product prices, settings for a program, counts of words in a text, and the data that web services send back as JSON. If you want to write real Python programs, you will use dictionaries in nearly every one.

In this tutorial, we start with what a dictionary is and how to create one. We then read values, change them, add new ones and loop through them, with every example run and its output shown. Next come the dictionary methods: get, values, items, len, pop, popitem, del and copy, plus others that the original version of this page missed, such as keys, update, setdefault and fromkeys. We finish with word counting, dictionary comprehension, nested dictionaries, the shallow copy trap, common errors and an FAQ.

Introduction to Dictionaries in Python

A dictionary is a collection of key value pairs written inside curly braces. Each key is connected to one value, with a colon between them, and pairs are separated by commas.

python
c = {1: "aa", 2: "bba", 3: "ab", 4: "ba"}

Here the keys are 1, 2, 3 and 4, and the values are the short texts. Keys can be numbers, text, or tuples, and values can be anything at all.

Here is what makes a dictionary a dictionary:

  • You can change, add and remove items after creating it. The original page called it immutable, which is wrong.
  • Ordered by insertion.Since Python 3.7, items stay in the order you added them. The original page called it unordered, which is true only for very old versions.
  • Looked up by key, not by position.You ask for c[2], meaning the value for key 2, not the item in second place.
  • Keys are unique.Adding a key that already exists replaces its value.
  • Keys must be unchangeable.Numbers, text and tuples are allowed. Lists are not.

Python Dictionary Examples

All the outputs below came from a real run on Python 3.13. The same code works on every version from 3.7 onward.

Read a Value by Its Key

python
c = {1: "aa", 2: "bba", 3: "ab", 4: "ba"}
print(c[2])
output
bba

Put the key inside square brackets. If the key does not exist, Python raises a KeyError. We will see how to avoid that when we reach the get method.

Change a Value

Use an equals sign. The original page wrote c[1] : ww with a colon, which does nothing. The colon belongs only inside the curly braces when you create the dictionary.

python
c = {1: "aa", 2: "bba", 3: "ab", 4: "ba"}
c[1] = "ww"
print(c)
output
{1: 'ww', 2: 'bba', 3: 'ab', 4: 'ba'}

Add a New Item

Assigning to a key that does not exist adds it.

python
c = {1: "aa", 2: "bba", 3: "ab", 4: "ba"}
c[1] = "ww"
c[5] = "new"
print(c)
output
{1: 'ww', 2: 'bba', 3: 'ab', 4: 'ba', 5: 'new'}

Loop Through a Dictionary

A plain loop gives you the keys. Remember that the line inside a loop must be indented, which the original page missed.

python
for key in c:
    print(key, end=" ")
print()
output
1 2 3 4 5

Python Dictionary Methods

Methods are built in tools that work on a dictionary. Here is the quick map before we try each one.

Dictionary methods at a glance
Method What it does Returns
get(key) Reads a value safely The value, or None if missing
keys() Lists the keys A view of all keys
values() Lists the values A view of all values
items() Lists key and value pairs A view of pairs
pop(key) Removes one item by key The removed value
popitem() Removes the last added item The removed pair
update(other) Adds or replaces many items None, the dictionary is changed
setdefault(key, value) Reads a key, adding it if missing The value
clear() Removes every item None
copy() Makes a shallow copy A new dictionary
fromkeys(keys, value) Builds a dictionary from keys A new dictionary

 

get()

get reads a value by key without crashing when the key is missing. With square brackets, a missing key raises a KeyError. With get, you get None, or a default value that you choose.

python
print(c.get(2))
print(c.get(9))
print(c.get(9, "not found"))
try:
    c[9]
except KeyError as error:
    print("KeyError:", error)
output
bba
None
not found
KeyError: 9

values()

values gives every value. Use it in a loop when you do not need the keys. The original page forgot the colon after the for line.

python
for value in c.values():
    print(value, end=" ")
print()
output
ww bba ab ba new

items()

items gives each key and value together, so you can unpack both in one loop. The original example printed c[2] every time, which hid what items does. Print the two loop variables instead.

for key, value in c.items():

python
for key, value in c.items():
    print(key, "->", value)
output
1 -> ww
2 -> bba
3 -> ab
4 -> ba
5 -> new

keys()

python
print(list(c.keys()))
output
[1, 2, 3, 4, 5]

len()

len counts the items, which means the number of key value pairs. You can also test whether a key exists with the in word, which checks keys and not values.

python
print(len(c), 3 in c, 99 in c)
output
5 True False

pop()

pop removes the item with the key you give, and hands back its value.

python
print(c.pop(2))
output
bba

popitem()

popitem removes the last item that was added and returns it as a pair. This order is guaranteed from Python 3.7. Before that, it removed an arbitrary item.

python
print(c.popitem())
output
(5, 'new')

del

The original page shows c.del(), which is a syntax error. In Python, del is a statement, and not a method. Use del with a key to remove one item, or del with the dictionary name to delete the whole variable.

python
del c[1]
print(c)
output
{3: 'ab', 4: 'ba'}

After del c, the name c no longer exists, and using it raises a NameError. If you want to empty a dictionary but keep it, use clear.

clear()

python
c.clear()
print(c)
output
{}

update()

update adds the items of another dictionary. If a key already exists, its value is replaced.

python
base = {"name": "Asha", "city": "Kolkata"}
base.update({"city": "Pune", "age": 29})
print(base)
output
{'name': 'Asha', 'city': 'Pune', 'age': 29}

From Python 3.9 you can also merge into a new dictionary with the vertical bar, which leaves the originals alone:

python
print(base | {"age": 30})
output
{'name': 'Asha', 'city': 'Pune', 'age': 30}

setdefault()

setdefault returns the value for a key. If the key is missing, it adds the key with the default you give, and returns that.

python
print(base.setdefault("role", "analyst"))
print(base.setdefault("city", "unused"))
output
analyst
Pune

The first call added role. The second left city alone, because it was already there.

fromkeys()

python
print(dict.fromkeys(["a", "b", "c"], 0))
output
{'a': 0, 'b': 0, 'c': 0}

copy()

copy makes a new dictionary with the same items. But it is a shallow copy, which means that any list or dictionary stored as a value is shared between the original and the copy. The original page does not mention this, and it causes real bugs.

python
import copy

original = {"scores": [80, 90]}
shallow = original.copy()
deep = copy.deepcopy(original)
original["scores"].append(100)
print("shallow:", shallow)
print("deep:", deep)
output
shallow: {'scores': [80, 90, 100]}
deep: {'scores': [80, 90]}

Adding 100 to the original list also changed the shallow copy, because both point to the same list. The deep copy was not affected. Use copy.deepcopy when your values are lists or dictionaries.

Useful Patterns

Counting Words

A very common job is counting how often things occur. The get method makes it short, because it returns 0 for a word seen for the first time.

python
words = "to be or not to be".split()
counts = {}
for word in words:
    counts[word] = counts.get(word, 0) + 1
print(counts)
output
{'to': 2, 'be': 2, 'or': 1, 'not': 1}

Dictionary Comprehension

You can build a dictionary in one line, in the same way as a list comprehension.

python
squares = {n: n * n for n in range(1, 6)}
print(squares)
output
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Nested Dictionaries

A value can be another dictionary. Use one pair of brackets for each level.

python
student = {"name": "Ravi", "marks": {"maths": 88, "science": 91}}
print(student["marks"]["science"])
output
91

This is the shape of most JSON data from the web, so you will meet it often.

Rules for Dictionary Keys

A key must be hashable, which in practice means it cannot be changed after it is created. Numbers, text and tuples work. A list does not, because a list can change.

python
bad = {[1, 2]: "list"}
print({(1, 2): "tuple works"})
output
TypeError: unhashable type: 'list'
{(1, 2): 'tuple works'}

Common Errors and Mistakes

Common dictionary mistakes
Mistake What happens Fix
Reading a missing key with c[key] KeyError Use c.get(key), or check with in first
Using a colon to change a value Nothing changes Use c[key] = value
Using a list as a key TypeError, unhashable Use a tuple
Changing a dictionary while looping over it RuntimeError Loop over list(c) or build a new dictionary
Treating copy as a full copy Nested values are shared Use copy.deepcopy
Writing c.del() Syntax error Use del c[key]
Forgetting indentation inside a loop IndentationError Indent the body by 4 spaces
Duplicate keys in one dictionary The last one wins silently Use unique keys

Dictionary Compared With List, Tuple and Set

Four collection types
Type Written as Changeable Best for
List [1, 2, 3] Yes An ordered collection that grows or shrinks
Tuple (1, 2, 3) No Fixed groups of values
Set {1, 2, 3} Yes Unique items and quick membership checks
Dictionary {“a”: 1} Yes Looking up values by a name or key

 

Try It Yourself: The Full Program

The complete program below holds every example in this tutorial. Copy it into a file, run it, and compare your output with what you see above.

python
import copy
import sys

print("Python", sys.version_info.major, sys.version_info.minor)

# Creating a dictionary and reading values
c = {1: "aa", 2: "bba", 3: "ab", 4: "ba"}
print(c[2])
print(c.get(2))
print(c.get(9))
print(c.get(9, "not found"))
try:
    c[9]
except KeyError as error:
    print("KeyError:", error)

# Changing and adding values
c[1] = "ww"
c[5] = "new"
print(c)

# Looping
for key in c:
    print(key, end=" ")
print()
for value in c.values():
    print(value, end=" ")
print()
for key, value in c.items():
    print(key, "->", value)
print(list(c.keys()))
print(len(c), 3 in c, 99 in c)

# Removing items
print(c.pop(2))
print(c.popitem())
del c[1]
print(c)
c.clear()
print(c)

# Merging and updating
base = {"name": "Asha", "city": "Kolkata"}
base.update({"city": "Pune", "age": 29})
print(base)
print(base | {"age": 30})
print(base.setdefault("role", "analyst"))
print(base.setdefault("city", "unused"))
print(dict.fromkeys(["a", "b", "c"], 0))

# Copy: shallow against deep
original = {"scores": [80, 90]}
shallow = original.copy()
deep = copy.deepcopy(original)
original["scores"].append(100)
print("shallow:", shallow)
print("deep:", deep)

# Counting words
words = "to be or not to be".split()
counts = {}
for word in words:
    counts[word] = counts.get(word, 0) + 1
print(counts)

# Dictionary comprehension and sorting
squares = {n: n * n for n in range(1, 6)}
print(squares)
print(dict(sorted(counts.items(), key=lambda pair: pair[1], reverse=True)))

# Nested dictionary
student = {"name": "Ravi", "marks": {"maths": 88, "science": 91}}
print(student["marks"]["science"])

# Keys must be unchangeable
try:
    bad = {[1, 2]: "list"}
except TypeError as error:
    print("TypeError:", error)
print({(1, 2): "tuple works"})
output
Python 3 13
bba
bba
None
not found
KeyError: 9
{1: 'ww', 2: 'bba', 3: 'ab', 4: 'ba', 5: 'new'}
1 2 3 4 5 
ww bba ab ba new 
1 -> ww
2 -> bba
3 -> ab
4 -> ba
5 -> new
[1, 2, 3, 4, 5]
5 True False
bba
(5, 'new')
{3: 'ab', 4: 'ba'}
{}
{'name': 'Asha', 'city': 'Pune', 'age': 29}
{'name': 'Asha', 'city': 'Pune', 'age': 30}
analyst
Pune
{'a': 0, 'b': 0, 'c': 0}
shallow: {'scores': [80, 90, 100]}
deep: {'scores': [80, 90]}
{'to': 2, 'be': 2, 'or': 1, 'not': 1}
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{'to': 2, 'be': 2, 'or': 1, 'not': 1}
91
TypeError: unhashable type: 'list'
{(1, 2): 'tuple works'}

A dictionary is a simple idea that you will use every day: a name, and the value that goes with it. Run the examples, break them on purpose to see the errors, and then use dictionaries to count, group and look up your own data. When you are comfortable, move on to the other Python data types and to working with files and JSON.

Popular Tags:

Python Dictionary Tutorial