Dictionary Basics
Unlike a list, which uses numeric indices (0, 1, 2, ...), a dictionary uses meaningful keys that you define. This makes dictionaries ideal for storing related information where the lookup key is semantic rather than positional.
Try it: How a dict Stores Keys
How a dictionary turns a key into a slot with a hash, what happens on a collision, why deleted keys leave a marker, and why the table grows.
How it works
- hash(key) gives a number; hash % table size gives the key's home slot.
- If that slot is taken by another key (a collision), probe the next slot.
- Deleting leaves a DELETED marker so lookups keep probing past it.
- When more than 2/3 of the slots are used, the table doubles and every key is re-inserted.
Default run (5 steps): A dict with 3 keys in 8 slots. Choose an operation. Example: d["mango"] = 5. … Done. 4 keys in 8 slots.
Simplified: Uses a small educational hash (Python's real string hash is randomised per run) and simple linear probing; CPython's probe order is more elaborate.
Loading the simulation…
Try it: Dictionary Operations
How a Python dict behaves under everyday operations: d[k] raises KeyError for a missing key while get() returns None or a default, in tests keys (not values), assignment adds a new key at the end but updates an existing key in place, del and pop remove pairs, and iteration, keys(), values() and items() follow insertion order — with keys() a live view and list(d.keys()) a frozen copy.
How it works
- A dict maps unique keys to values; the pairs are kept in the order the keys were first inserted (Python 3.7+).
- d[k] returns the value for k or raises KeyError: 'k'; d.get(k) returns None and d.get(k, default) the default instead.
- k in d tests the keys only; testing a value needs v in d.values(); len(d) counts pairs.
- d[k] = v adds a new pair at the end when k is new, and replaces the value in place (same position) when k already exists; update() does this for each pair.
- del d[k] and d.pop(k) remove a pair (KeyError if missing; pop returns the value, or the default if one is given).
- keys(), values() and items() are views of the current dict; list(d.keys()) copies the keys at that moment. Filtering builds a NEW dict of the pairs that pass a test.
Default run (3 steps): d = {'apple': 3, 'fig': 7, 'pear': 5} — 3 key-value pairs, kept in insertion order. Choose an operation. Example: d.get('kiwi', 0). … The key is missing, so get returns the default 0 instead of raising KeyError. d is not changed.
Simplified: String keys (short lowercase words) and small int values, at most 8 pairs. The lab models what the operations do, not how CPython stores the dict (see the hashing lab for that). Every operation's result, error text, printed output and view contents match CPython 3.12 on 150 random operation sequences.
Loading the simulation…
Why Python Has No Switch Statement
Many programming languages have a switch statement that lets you branch to different code paths based on a single value. Python does not have a switch statement. Instead, you can use an if..elif..else statement to accomplish the same goal. However, there is a third option that is often faster and cleaner: a dictionary.
This lesson introduces dictionaries as a practical alternative to branching logic. You will learn what a dictionary is, how it stores information, and when to reach for it instead of writing multiple conditional statements.
What Is a Dictionary?
A dictionary is one of Python's four built-in data structures (the others being list, tuple, and set). A dictionary works like a real-world address book: you look up a person by their name and get their contact details. In a dictionary, you associate keys (like names) with values (like details). The key must be unique, just as you cannot find the correct information if two people have the exact same name.
A key-value pair is a single entry in a dictionary. The key is what you use to look something up, and the value is what you get back. Keys must be unique within a single dictionary, but values can repeat.
Unlike a list, which uses numeric indices (0, 1, 2, ...), a dictionary uses meaningful keys that you define. This makes dictionaries ideal for storing related information where the lookup key is semantic rather than positional.
Dictionary Lookup vs. If-Elif-Else Branching
To understand why dictionaries matter, consider how a program makes decisions. When you write if..elif..else statements, the program checks each condition in order until one is true, then executes that branch. This is sequential: the program must evaluate conditions one by one. A dictionary lookup, by contrast, goes directly to the value associated with a key. The program does not check multiple conditions; it simply retrieves the value in a single step.
This difference becomes significant when you have many conditions to check. With if..elif..else, the program might need to evaluate ten or twenty conditions before finding a match. With a dictionary, the lookup is nearly instantaneous regardless of how many key-value pairs exist.
How Dictionary Lookup Works
When you provide a key to a dictionary, Python uses an internal mechanism called hashing to find the associated value. The key is transformed into a hash value, which points to a location in memory where the value is stored. This process is extremely fast, even for dictionaries with thousands of entries.
The key must be unique because the hashing mechanism assumes each key points to exactly one value. If two keys were identical, Python would not know which value to return.
Worked Example: Contact Lookup
Using a Dictionary to Store and Retrieve Contact Information
You need to store contact information for three people: Alice (age 30), Bob (age 25), and Carol (age 28). You want to retrieve a person's age by looking up their name. How would you structure this with a dictionary?
- 1Identify keys and values
The keys are the names (Alice, Bob, Carol) because you will look up by name. The values are the ages (30, 25, 28) because that is what you want to retrieve.
- 2Create the dictionary
In Python, you write a dictionary using curly braces with key-value pairs separated by colons. Each pair is separated by a comma. The structure is {key1: value1, key2: value2, key3: value3}.
- 3Retrieve a value
To get Alice's age, you use the syntax
dictionary_name[key]. Python looks up the key and returns the associated value immediately. - 4Verify uniqueness
Each name appears only once as a key. If you tried to add another entry with the key Alice, it would overwrite the first entry. This is why keys must be unique.
A dictionary with three key-value pairs allows you to retrieve any person's age in a single lookup operation, without writing multiple if statements.
Dictionary vs. If-Elif-Else in Practice
Consider a program that translates color names to their hexadecimal codes. You could write this with if..elif..else or with a dictionary. Here is how the two approaches differ in structure and readability.
#FF0000#FF0000Both approaches produce the same output. However, the dictionary approach is more concise and scales better. If you need to add ten more colors, the dictionary grows by ten lines (one per key-value pair), while the if..elif..else approach grows by ten elif blocks. Additionally, the dictionary lookup is faster because Python does not need to evaluate multiple conditions.
Common Mistakes with Dictionaries
Common mistake Using a non-unique key
What it looks likemy_dict = {"name": "Alice", "name": "Bob"}Why it failsThe second assignment overwrites the first. The dictionary will contain only one entry with key "name" and value "Bob". You lose the first value.
Do this insteadEnsure each key is unique. If you need to store multiple people, use different keys or a different data structure like a list of dictionaries.
Common mistake Accessing a key that does not exist
What it looks likemy_dict = {"name": "Alice"}; print(my_dict["age"])Why it failsPython raises a
KeyErrorbecause the key "age" does not exist in the dictionary. The program crashes.Do this insteadCheck if the key exists before accessing it, or use the .get() method which returns None (or a default value) if the key is not found.
Common mistake Forgetting that keys must be unique
What it looks likeAssuming you can have two entries with the same key and retrieve both
Why it failsA dictionary can only store one value per key. If you need multiple values for the same key, use a list or a different data structure.
Do this insteadUse a list of dictionaries or a dictionary with a list as the value if you need to associate multiple values with a single key.
Common mistake Using a mutable object as a key
What it looks likemy_dict = {[1, 2]: "value"}Why it failsLists are mutable and cannot be used as dictionary keys. Python raises a
TypeError. Only immutable objects (strings, numbers, tuples) can be keys.Do this insteadUse immutable objects as keys. If you need a compound key, use a tuple instead of a list.
When to Use a Dictionary
Use a dictionary when you need to look up a value by a meaningful key, especially if you have many possible keys. Dictionaries are ideal for storing configuration settings, translating between codes, mapping names to values, or any situation where you would otherwise write a long if..elif..else chain.
Do not use a dictionary if you need to preserve order in a specific way (though modern Python dictionaries do preserve insertion order), or if you need to store data that does not fit the key-value model. For example, if you have a list of numbers and need to access them by position, use a list, not a dictionary.
Practice: Build Your Own Dictionary
Create a dictionary that maps programming language names to their primary use. Include at least four languages. Then, write code to retrieve the primary use of one language by looking up its name in the dictionary. Finally, explain why a dictionary is better than an if..elif..else statement for this task.
Hints
- Start by deciding which languages to include and what their primary uses are.
- Use curly braces and colons to create the dictionary.
- Access a value by writing
dictionary_name[key]. - Think about how many elif statements you would need if you used branching instead.
Summary
- 1Python has no switch statement, but you can use if..elif..else or a dictionary to branch based on a value.
- 2A dictionary stores key-value pairs, where keys must be unique and are used to look up values.
- 3Dictionary lookup is faster than if..elif..else because Python goes directly to the value instead of checking multiple conditions sequentially.
- 4Use a dictionary when you need to map meaningful keys to values, especially if you have many possible keys.
- 5Keys must be unique and immutable (strings, numbers, tuples). Attempting to access a non-existent key raises a
KeyError.
At a glance
- A dictionary is a data structure that stores key-value pairs, allowing you to look up a value by providing its key.
- Dictionaries are faster and more readable than if..elif..else statements when you have many conditions to check.
- Keys must be unique within a dictionary; attempting to create duplicate keys overwrites the previous value.
- Use dictionaries when you need semantic lookups (by name, code, or label) rather than positional access (by index).
- Only immutable objects (strings, numbers, tuples) can be dictionary keys; mutable objects like lists cannot.