Recommended Free Tools
iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
A Python dictionary stores values under unique keys. Use a key to retrieve or change its value, check membership with in, and loop through entries with .items(). For example, {"name": "Ada", "language": "Python"} maps the key "name" to the value "Ada".
Create a dictionary
Use braces with key-value pairs to create a dictionary. Separate each key and value with a colon, and separate entries with commas:
person = {"name": "Ada", "language": "Python"}
For an empty dictionary, write {}. You can also create one with dict(), including from keyword arguments or an iterable of key-value pairs:
settings = dict(theme="dark", alerts=True)
pairs = dict([("host", "localhost"), ("port", 8000)])
A dictionary comprehension builds a dictionary from an iterable. This example maps each number from 0 through 3 to its square:
#1 Best Overall
squares = {n: n * n for n in range(4)}
See the Python 3.14.7 tutorial on dictionaries for additional creation patterns.
Read, add, and change entries
Retrieve a value
Use square brackets with a key to retrieve its value:
print(person["name"]) # Ada
If the key is absent, this lookup raises KeyError. How to handle that case depends on whether a missing key is an error or should have a fallback.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallCrashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteRank #2
Add or replace an entry
Assign to a key to add a new entry or replace the value of an existing one:
person["city"] = "London" # adds a key
person["language"] = "Python 3" # replaces its value
Each key appears at most once. Assigning to an existing key updates its value rather than creating a duplicate entry.
Handle missing keys and test membership
Use get() when you want a lookup to return a fallback instead of raising an error. With no fallback argument, d.get(key) returns None if the key is absent; with a fallback, it returns that value:
nickname = person.get("nickname")
score = person.get("score", 0)
Use key in d to check whether a key exists. This matters when None is a possible stored value: get() alone cannot distinguish an absent key from a key whose value is None.
if "nickname" in person:
print(person["nickname"])
if "middle_name" in person:
print(person["middle_name"]) # runs even if the value is None
Membership tests keys, not values. To check values instead, use value in d.values().
Remove an entry
Use del d[key] to remove an entry. As with bracket lookup, deleting a key that is not present raises KeyError; test membership first if absence is expected.
if "city" in person:
del person["city"]
Loop through dictionary contents
A plain loop over a dictionary yields its keys. Use .items() to access each key and value together:
for key in person:
print(key)
for key, value in person.items():
print(key, value)
The .keys(), .values(), and .items() methods provide views of the dictionary’s keys, values, and key-value pairs. They reflect the dictionary’s contents, so changes to the dictionary are visible through the views.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Repair Windows errors before they cause bigger problemsFix Now →Merge entries with update()
Call update() to add entries from another mapping or an iterable of key-value pairs. When an incoming key already exists, its value replaces the current value:
Best Value
defaults = {"theme": "light", "alerts": True}
user_settings = {"theme": "dark"}
defaults.update(user_settings)
# defaults is now {"theme": "dark", "alerts": True}
More details are in the Python 3.14.7 built-in types reference for dict.
Choose suitable dictionary keys
Dictionary keys need stable hash behavior. Strings and numbers are common keys. Tuples can also be keys if their contents are themselves suitable; a tuple containing a list is not suitable.
Lists and dictionaries cannot be keys because they are mutable. Changing a key after it has been inserted could invalidate the hash-based lookup that dictionaries rely on. Values do not have this restriction: a dictionary can store mutable values such as lists.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
scores = {"Ada": 98, "Lin": 92}
# A list is fine as a value:
groups = {"team_a": ["Ada", "Lin"]}
# A list cannot be used as a key:
# invalid = {["Ada", "Lin"]: "team_a"}
Understand dictionary order
Dictionary insertion order is a language guarantee in Python 3.7 and later. Python 3.6’s CPython implementation preserved order, but it was an implementation detail rather than a language guarantee. The Python language reference specifies that keys are produced in the order they were added.
- Replacing the value for an existing key does not change its position.
- Deleting a key and inserting it again places it at the end.
Example: count values with a dictionary
A dictionary is useful when each item needs to be associated with a count. The following loop starts a missing count at zero, then increments it for each word:
words = ["red", "blue", "red", "green", "blue", "red"]
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
print(counts)
# {'red': 3, 'blue': 2, 'green': 1}
This works because get(word, 0) supplies zero for a word not yet in the dictionary, while later occurrences read and increment the stored count.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Scan for outdated or missing drivers - takes under a minute3Repair Windows errors before they cause bigger problems

