How to Make a Dictionary in Python
What you’ll build or solve
You’ll create dictionaries in Python, add and update key-value pairs, and read values safely without KeyError.
When this approach works best
This approach works best when you need to:
Learn Python on Mimo
- Store related data by name, like
{"name": "Anna", "city": "Boston"}. - Look up values fast by a key, like
prices["apple"]. - Count or group items, like counting words or grouping orders by status.
Avoid this approach when:
- You only need items in order and access by position. A list is simpler.
- You need multiple values for the same key. Use a list as the value, like
{"tag": ["a", "b"]}.
Prerequisites
- Python 3 installed
- You know what variables are
- You know what a list is
- You can run a short Python script
Step-by-step instructions
1) Create a dictionary
Use curly braces with key: value pairs.
Python
person = {"name": "Anna", "age": 29, "city": "Boston"}
print(person)
Keys are usually strings, but they can also be numbers or tuples.
2) Start empty and add items
This works well when you build data step by step.
Python
person = {}
person["name"] = "Ana"
person["age"] = 29
print(person)
What to look for:
Assigning person["age"] = 29 creates the key if it is missing, or updates it if it already exists.
3) Read values safely
Use square brackets when you are sure the key exists. Use get() when it might not.
Python
person = {"name": "Ana", "age": 29}
print(person["name"])
print(person.get("city"))
get() returns None if the key is missing. You can provide a default value:
Python
print(person.get("city", "Unknown"))
4) Update or overwrite a value
Assign to an existing key to change its value.
Python
person = {"name": "Ana", "age": 29}
person["age"] = 30
print(person)
If the key does not exist, this assignment creates it.
5) Loop through keys and values
Looping helps you print, transform, or validate dictionaries.
Python
person = {"name": "Anna", "age": 29, "city": "Boston"}
for key, value in person.items():
print(key, value)
If you only need keys, use for key in person:.
If you only need values, use for value in person.values():.
Examples you can copy
1) Count words in a sentence
Python
text = "learn python learn dictionaries"
counts = {}
for word in text.split():
counts[word] = counts.get(word, 0) + 1
print(counts)
This pattern avoids KeyError by using get() with a default.
2) Build a simple price lookup
Python
prices = {"apple": 1.2, "banana": 0.8, "orange": 1.5}
item = "banana"
print(prices.get(item, "missing"))
3) Group tasks by status
Python
tasks = [
("Write outline", "todo"),
("Draft post", "doing"),
("Publish", "done"),
]
by_status = {}
for title, status in tasks:
if status not in by_status:
by_status[status] = []
by_status[status].append(title)
print(by_status)
Each key stores a list of related items.
Common mistakes and how to fix them
Mistake 1: Forgetting the : between key and value
You might write:
Python
person = {"name" "Ana"}
Why it breaks:
Dictionaries require key: value pairs, so this causes a syntax error.
Correct approach:
Python
person = {"name": "Ana"}
Mistake 2: Using an unhashable type as a key
You might write:
Python
bad_key = ["a", "b"]
data = {bad_key: 1}
Why it breaks:
Lists can change, so Python does not allow them as dictionary keys.
Correct approach:
Python
good_key = ("a", "b")
data = {good_key: 1}
print(data)
Tuples are immutable, so Python allows them as keys.
Mistake 3: Getting a KeyError when reading a missing key
You might write:
Python
person = {"name": "Ana"}
print(person["city"])
Why it breaks:
Square bracket access fails if the key does not exist.
Correct approach:
Python
person = {"name": "Ana"}
print(person.get("city", "Unknown"))
Troubleshooting
If you see KeyError, switch to dict.get(key) or check if key in dict_name: before accessing.
If you see SyntaxError near a dictionary literal, check for missing : or missing commas between pairs.
If you see TypeError: unhashable type, you used a mutable type like a list as a key. Use a string, number, or tuple instead.
If your loop prints only keys, use .items() to get both keys and values.
Quick recap
- Create a dictionary with
{}andkey: valuepairs. - Add or update items with
d[key] = value. - Read safely with
d.get(key, default)when keys may be missing. - Update values by assigning to an existing key.
- Loop with
for key, value in d.items():to access both.
Join 40M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot