Python DictionariesGet Certified
What Is a Dictionary in Python?
A dictionary is a collection that stores data as key-value pairs. Each key works like a label, and the value is the data attached to that label. Instead of remembering that the third item of a list is a phone number, you can simply ask the dictionary for the value stored under the key "phone".
A dictionary is written with curly braces {}. Each pair is written as key: value, and the pairs are separated by commas. The type of a dictionary is dict.
This structure is useful whenever information has a clear name or identifier, such as a student’s details, product prices, or application settings. Each key provides a direct way to access its associated data, making dictionaries convenient for organizing related information. You will use them frequently when working with records and structured data in Python.
- Key-value pairs:
{"name": "Charlotte"}connects the key"name"to the value"Charlotte". - Fast lookup: you find a value by its key, not by its position, and the lookup is very fast even for large dictionaries.
- Unique keys: every key can appear only once. Assigning to an existing key replaces its value.
- Hashable keys: keys must be immutable types such as strings, numbers, or tuples. A list cannot be a key.
- Any values: values can be of any type, including lists and other dictionaries.
- Ordered and mutable: since Python 3.7 a dictionary remembers the order in which keys were added, and you can change it after creation.
Creating a Dictionary and Reading Values
You can create a dictionary with curly braces or with the dict() function. To read a value, put the key in square brackets. If the key does not exist, Python raises a KeyError. The get() method is a safer choice, because it returns None or a default value that you supply instead of raising an error.
When choosing between these access methods, consider whether the key is guaranteed to be present. Square-bracket access is suitable when missing data should be treated as an error, while get() is helpful when a value is optional. These approaches make it easier to handle records that may contain different information.
Try It: Create a Dictionary and Read Its Values
Click Test My Code to run the program. Then change the keys and values to describe yourself and run it again.
get(), and prints the number of pairs.student = {"name": "Charlotte", "age": 21, "course": "Python"}
print(student)
print(student["name"])
print(student.get("grade", "Not graded"))
print(len(student))student = {...} creates a dictionary with three key-value pairs. The keys "name", "age", and "course" are strings, and the values are a string, an integer, and another string.{'name': 'Charlotte', 'age': 21, 'course': 'Python'}. The pairs appear in the order in which they were written.student["name"] returns the value stored under the key "name", so the output is Charlotte."grade" key, so get() returns the default value that was given as the second argument. The output is Not graded. Writing student["grade"] would have raised a KeyError.len() returns the number of key-value pairs, so the output is 3.Adding, Changing, and Removing Items
Dictionaries are mutable. Assigning to a key that does not exist adds a new pair, and assigning to a key that already exists replaces its value. To remove items you can use:
These operations let you maintain a dictionary as information changes. For example, a contact list can receive new entries, existing phone numbers can be corrected, and outdated contacts can be deleted. Choose the removal method according to whether you also need to use the value that was removed.
pop(key): removes the key and returns its value.del d[key]: removes the key without returning anything.popitem(): removes and returns the last inserted pair.clear(): removes every pair and leaves an empty dictionary.
Try It: Add, Update, and Remove
Click Test My Code and follow the changes step by step. Then try removing a different name.
pop().phone = {"Charlotte": "555-0101", "Ravi": "555-0102"}
phone["Meena"] = "555-0103"
phone["Ravi"] = "555-0999"
removed = phone.pop("Charlotte")
del phone["Meena"]
print(phone)
print("Removed:", removed)"Meena" does not exist yet, so this assignment adds a new pair to the dictionary."Ravi" already exists, so the assignment replaces the old number with "555-0999". A dictionary never holds the same key twice.pop("Charlotte") removes that pair and returns the value "555-0101", which is stored in removed.del phone["Meena"] removes the pair for "Meena". Unlike pop(), it gives nothing back.{'Ravi': '555-0999'}.Removed: 555-0101.Looping Through a Dictionary
A for loop over a dictionary gives you its keys. Three view methods let you choose what to loop over:
Looping is useful when you need to display, calculate, or process every entry without accessing each key individually. The method you choose determines which part of the data is available during each iteration. For tasks involving both labels and their associated information, working with pairs can make the code easier to follow.
keys(): all the keys.values(): all the values.items(): all the pairs, as(key, value)tuples that you can unpack directly in the loop.
Try It: Keys, Values, and Items
Click Test My Code. Then add a fourth fruit to the dictionary and run it again.
prices = {"apple": 40, "banana": 10, "mango": 80}
for fruit in prices:
print(fruit)
print(list(prices.values()))
for fruit, price in prices.items():
print(fruit, "costs", price)
print(sum(prices.values()))for loop over a dictionary takes the keys one at a time and stores each in fruit.apple, banana, and mango, each on its own line.prices.values() gives a view of the values. list() turns it into a list, so the output is [40, 10, 80].items() gives (key, value) pairs. Writing fruit, price after for unpacks every pair into two variables.apple costs 40, banana costs 10, and mango costs 80.sum() adds all the values, so the output is 130.Counting with get() and Checking Keys
The in operator checks whether a key exists in a dictionary. It does not search the values. Combined with get(key, default), it leads to one of the most common dictionary patterns: counting how often something appears.
This pattern is especially helpful when processing repeated data, such as words in a sentence, votes in a poll, or items sold in a shop. Each time an item appears, its stored count can be increased. Starting with a default of zero means you can handle both new and previously encountered items in the same expression.
Try It: Count Words
Click Test My Code. Then change the sentence and see how the counts change.
get() returns 0, so one is added each time a word is seen. It then checks whether two words are keys of the dictionary.text = "to be or not to be"
counts = {}
for word in text.split():
counts[word] = counts.get(word, 0) + 1
print(counts)
print("be" in counts, "xyz" in counts)text.{} creates an empty dictionary that will collect the counts.text.split() breaks the sentence into a list of six words. The loop handles one word at a time.counts.get(word, 0) returns the current count, or 0 if the word has not been seen. Adding 1 and storing the result back creates the key or updates it.{'to': 2, 'be': 2, 'or': 1, 'not': 1}.True False, because "be" is a key and "xyz" is not.Merging and Updating Dictionaries
The update() method copies the pairs of one dictionary into another. If a key exists in both, the new value wins. Python 3.9 and later also provide the merge operator |, which builds a new dictionary and leaves both originals unchanged.
Merging is useful when information comes from multiple sources, such as combining default application settings with a user’s preferences. Before combining dictionaries, consider which source should take priority when the same key appears more than once. The order of the merge determines which value is retained for overlapping keys.
Try It: Combine Default and User Settings
Click Test My Code. Notice that the user’s font size replaces the default one.
defaults = {"theme": "light", "font": 14}
user = {"font": 18, "language": "en"}
settings = defaults | user
print(settings)
defaults.update(user)
print(defaults == settings)
print(settings.keys())"font" appears in both dictionaries.defaults | user creates a new dictionary. When a key is in both, the value from the right-hand dictionary is used, so the font becomes 18.{'theme': 'light', 'font': 18, 'language': 'en'}.defaults.update(user) changes defaults itself by copying in every pair from user.True.dict_keys(['theme', 'font', 'language']), a view of all the keys in order.Reading Values into a Dictionary
Dictionaries are an excellent way to bundle related input into a single object. Remember that input() always returns text, so convert numbers with int() or float() first. You can also store the result of a comparison as a value.
This approach is useful for collecting information from forms, command-line programs, or simple interactive applications. Once the input has been converted to the correct data type, it can be stored alongside other related fields. You can then retrieve or process the complete record using meaningful keys instead of separate variables.
Try It: Build a Record from input()
The Program Input box is already filled with two lines: Charlotte and 72. Click Run Code straight away, then try different values.
name = input("Name: ")
marks = int(input("Marks: "))
record = {"name": name, "marks": marks}
record["passed"] = marks >= 40
print(record)
print(record["name"], "passed:", record["passed"])input() reads the first line of the Program Input box as text and stores it in name.int() converts it to a whole number. If it is not a whole number, Python stops with a ValueError."name" and "marks".marks >= 40 is True or False. The result is stored under the new key "passed".{'name': 'Charlotte', 'marks': 72, 'passed': True}.Charlotte passed: True.Nested Dictionaries and References
The value of a dictionary can be another dictionary or a list. This lets you describe structured data, such as a class of students, in a single variable. You reach the inner data by chaining keys: students["s1"]["name"].
Like variables in general, a dictionary holds references. Changing a list that sits inside a dictionary changes it for every name that refers to that list. Use copy() for a shallow copy, or copy.deepcopy() from the copy module when nested objects must be independent too.
Nested structures are useful when one record contains several related categories of information. For example, each student can have a name, marks, and contact details stored together. When accessing these values, follow the structure one level at a time so that you can identify which dictionary or list contains the information you need.
Try It: A Dictionary of Dictionaries
Click Test My Code. Then add a third student and run it again.
students = {
"s1": {"name": "Charlotte", "marks": [80, 90]},
"s2": {"name": "Ravi", "marks": [70, 65]},
}
print(students["s1"]["name"])
students["s2"]["marks"].append(75)
print(students["s2"]["marks"])
for sid, info in students.items():
print(sid, info["name"], sum(info["marks"]) / len(info["marks"]))"s1" is itself a dictionary with a name and a list of marks."s2" has the same structure. A trailing comma after the last pair is allowed.students["s1"] returns the inner dictionary, and ["name"] then reads from it. The output is Charlotte.students["s2"]["marks"] is a list, so append(75) adds a third mark to it. The dictionary itself did not need to be reassigned.[70, 65, 75].items() gives each id together with its inner dictionary, which is stored in info.s1 Charlotte 85.0 and s2 Ravi 70.0.Dictionary Comprehensions and Sorting
A dictionary comprehension builds a dictionary in one line, in the form {key: value for item in iterable}. Because a dictionary is not sorted by value, use sorted() on items() with a key function to rank the pairs, and use max() or min() with key=d.get to find the key with the largest or smallest value.
Comprehensions are especially convenient when you want to transform an existing sequence into a new collection of related pairs. Sorting helps when the order of results matters, such as displaying a leaderboard or comparing prices. Keep the expression readable by using a regular loop when the transformation requires several steps or complex conditions.
Try It: Build and Rank a Dictionary
Click Test My Code. Then change the range or the scores and run it again.
scores = {"Charlotte": 88, "Ravi": 72, "Meena": 95}
squares = {n: n * n for n in range(1, 6)}
print(squares)
ranked = sorted(scores.items(), key=lambda item: item[1], reverse=True)
print(ranked)
print(max(scores, key=scores.get))n from 1 to 5 the comprehension creates the pair n: n * n, so every number is connected to its square.{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}. Keys do not have to be strings, and numbers work well too.sorted() turns the pairs into a list. The key function picks the score, which is the item at index 1 of each pair, and reverse=True puts the highest score first.[('Meena', 95), ('Charlotte', 88), ('Ravi', 72)].max() goes through the keys and uses scores.get to compare their values. It returns the key with the largest value, so the output is Meena.Tip: To loop over a dictionary and change its size at the same time, loop over a copy such aslist(d.keys()). Adding or removing keys while looping over the dictionary itself raises aRuntimeError.
Common Mistakes with Dictionaries
Dictionary errors often happen when a program expects a key or data type that is not actually present. Some mistakes produce an immediate exception, while others allow the program to run but return an unexpected result. Understanding how keys, values, and references behave makes these problems easier to recognize and prevent.
- KeyError: reading a key that does not exist with
d["x"]raisesKeyError. Used.get("x"), or check with"x" in dfirst. - Using a list as a key:
{[1, 2]: "a"}raisesTypeError: unhashable type. Use a tuple such as(1, 2)instead. - Expecting duplicate keys: writing the same key twice keeps only the last value.
- Confusing
{}with an empty set:{}creates an empty dictionary. Useset()for an empty set. - Checking values with
in:"Charlotte" in dtests keys only. To test values, use"Charlotte" in d.values(). - Assigning instead of copying:
b = agives the same dictionary a second name. Usea.copy()for an independent copy. - Changing size while looping: adding or deleting keys during a loop over the same dictionary causes a
RuntimeError. - Shadowing the built-in name: naming a variable
dicthides thedict()function. Choose a descriptive name such asstudent.
Good Habits for Using Dictionaries
Well-organized dictionaries make programs easier to understand, maintain, and extend. Use names that clearly describe the information stored under each key, and keep related values grouped together. When a dictionary becomes deeply nested or difficult to navigate, consider simplifying its structure or separating complex data into smaller, clearly named parts.
- Choose clear, consistent keys, such as lowercase strings like
"first_name". - Use
get()with a default when a key may be missing. - Loop with
items()when you need both the key and the value. - Use a dictionary instead of many separate variables when values belong together.
- Use a dictionary instead of a long
if/elifchain when you only map one value to another. - Keep nested structures shallow, so that the code stays easy to read.
Key Takeaways
Python dictionaries provide a flexible way to organize information using meaningful keys. You can create them, retrieve and modify values, process their contents with loops, and combine data from different sources. As you work through the examples, focus on choosing suitable keys and selecting the operation that best matches the task.
- A dictionary stores key-value pairs inside curly braces and is created with
{}ordict(). - Keys are unique and must be immutable. Values can be anything.
- Read with
d[key]or the saferd.get(key, default), and add or change withd[key] = value. - Remove with
pop(),del,popitem(), orclear(). - Loop with
keys(),values(), anditems(). A plainforloop gives the keys. - Merge with
update()or the|operator, and build with dictionary comprehensions. - Dictionaries remember insertion order and hold references, so use
copy()when you need an independent copy.
Frequently Asked Questions
The following questions cover common situations you may encounter when creating and working with dictionaries. They explain how Python handles keys, missing values, iteration, ordering, and combining data. Use these answers as a quick reference when reviewing the examples or troubleshooting your own dictionary-based programs.
What is a dictionary in Python?
A dictionary is a built-in collection that stores data as key-value pairs inside curly braces, for example {“name”: “Charlotte”, “age”: 21}. You use a key to look up its value quickly. Dictionaries are mutable, so you can add, change, and remove pairs after creating them.
How do I create a dictionary in Python?
Write key: value pairs separated by commas inside curly braces, for example d = {“a”: 1, “b”: 2}. You can also use the dict() function, such as dict(a=1, b=2), or write {} to create an empty dictionary.
What is the difference between d[key] and d.get(key)?
d[key] raises a KeyError when the key does not exist. d.get(key) returns None instead, and d.get(key, default) returns the default value that you provide. Use get() when a key might be missing.
Can a Python dictionary have duplicate keys?
No. Every key in a dictionary is unique. If you assign to a key that already exists, its old value is replaced. If the same key appears twice in a dictionary literal, only the last value is kept.
What can be used as a dictionary key?
A key must be hashable, which means it must be an immutable type such as a string, number, boolean, or tuple of immutable items. A list, set, or dictionary cannot be used as a key because they can be changed.
How do I loop through a dictionary in Python?
A for loop over a dictionary gives its keys. Use d.values() to loop over the values, and d.items() to get both at once, for example for key, value in d.items(). The keys come in the order in which they were inserted.
Are Python dictionaries ordered?
Yes. Since Python 3.7 a dictionary keeps the order in which its keys were first inserted. Updating the value of an existing key does not change its position. Dictionaries are still looked up by key, not by numeric index.
How do I merge two dictionaries in Python?
Use a | b in Python 3.9 and later to create a new merged dictionary, or a.update(b) to add the pairs of b into a. If a key is in both, the value from the second dictionary is used.