Academic Block

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.

What this code does: It creates a dictionary that describes a student, prints the whole dictionary, reads one value by its key, looks up a missing key safely with 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))

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.

What this code does: It builds a small phone book, adds a new contact, replaces an existing number, removes two contacts in two different ways, and prints what is left together with the number that was removed with 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)

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.

What this code does: It stores the price of three fruits. It loops over the keys, prints the values as a list, loops over the key-value pairs to print a sentence for each fruit, and finally adds all the prices together.
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()))

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.

What this code does: It splits a sentence into words and counts every word in a dictionary. For a new word 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)

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.

What this code does: It merges a dictionary of default settings with a dictionary of user settings into a new dictionary. It then updates the defaults in place and confirms that both approaches give the same result.
defaults = {"theme": "light", "font": 14}
user = {"font": 18, "language": "en"}
settings = defaults | user
print(settings)
defaults.update(user)
print(defaults == settings)
print(settings.keys())

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.

What this code does: It reads a name and a mark, stores them in a dictionary, adds a new key that records whether the mark is 40 or more, and prints the record and a short summary.
name = input("Name: ")
marks = int(input("Marks: "))

record = {"name": name, "marks": marks}
record["passed"] = marks >= 40
print(record)
print(record["name"], "passed:", record["passed"])

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.

What this code does: It stores two students, each as a dictionary with a name and a list of marks. It reads a nested value, adds a mark to one student’s list, and loops over all students to print each average mark.
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"]))

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.

What this code does: It builds a dictionary of squares with a comprehension, ranks three students by score from highest to lowest, and finds the name of the top scorer.
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))
Tip: To loop over a dictionary and change its size at the same time, loop over a copy such as list(d.keys()). Adding or removing keys while looping over the dictionary itself raises a RuntimeError.

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"] raises KeyError. Use d.get("x"), or check with "x" in d first.
  • Using a list as a key: {[1, 2]: "a"} raises TypeError: 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. Use set() for an empty set.
  • Checking values with in: "Charlotte" in d tests keys only. To test values, use "Charlotte" in d.values().
  • Assigning instead of copying: b = a gives the same dictionary a second name. Use a.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 dict hides the dict() function. Choose a descriptive name such as student.

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/elif chain 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 {} or dict().
  • Keys are unique and must be immutable. Values can be anything.
  • Read with d[key] or the safer d.get(key, default), and add or change with d[key] = value.
  • Remove with pop(), del, popitem(), or clear().
  • Loop with keys(), values(), and items(). A plain for loop 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.

Ready for the next step?Learn how to build lists and dictionaries in a single line.
Next: List & Dictionary Comprehensions →