Dictionary Basics
There is no switch statement in Python. You can use an if..elif..else statement to do the same thing (and in some cases, use a dictionary to do it quickly)
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?
Identify 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.
Create 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}.
Retrieve 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.
Verify 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
Using a non-unique key
The second assignment overwrites the first. The dictionary will contain only one entry with key "name" and value "Bob". You lose the first value.
Fix:
Ensure each key is unique. If you need to store multiple people, use different keys or a different data structure like a list of dictionaries.Accessing a key that does not exist
Python raises a KeyError because the key "age" does not exist in the dictionary. The program crashes.
Fix:
Check 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.Forgetting that keys must be unique
A 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.
Fix:
Use a list of dictionaries or a dictionary with a list as the value if you need to associate multiple values with a single key.Using a mutable object as a key
Lists are mutable and cannot be used as dictionary keys. Python raises a TypeError. Only immutable objects (strings, numbers, tuples) can be keys.
Fix:
Use 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
- Python has no switch statement, but you can use if..elif..else or a dictionary to branch based on a value.
- A dictionary stores key-value pairs, where keys must be unique and are used to look up values.
- Dictionary lookup is faster than if..elif..else because Python goes directly to the value instead of checking multiple conditions sequentially.
- Use a dictionary when you need to map meaningful keys to values, especially if you have many possible keys.
- Keys must be unique and immutable (strings, numbers, tuples). Attempting to access a non-existent key raises a KeyError.
Key Takeaways
- 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.