Learn Why to Use Dictionaries in Python: Absolute Beginners Tutorial

Python gives you several ways to organize data, but dictionaries stand apart for one critical reason: they let you find any value instantly using a meaningful label. If you have ever stored a username in one list and an email in another, then struggled to keep them in sync, dictionaries solve that problem by design.

What Is a Dictionary and Why Does It Exist

A Python dictionary is a collection of key-value pairs wrapped in curly braces. Every key points to exactly one value, and you use that key to retrieve the value later. Think of it the way you would use a real-world phone book: you look up someone's name (the key) to find their number (the value). You do not need to know what position the entry sits in. You just need the name.

The Python documentation describes a dictionary as a set of key: value pairs where keys must be unique within a single dictionary. Strings and numbers can always serve as keys. Tuples work too, as long as they contain only immutable elements. Lists cannot be keys because they can be changed after creation.

python
# A simple dictionary mapping student data
student = {
    "name": "Jordan",
    "age": 22,
    "major": "Computer Science"
}

# Retrieve a value by its key
print(student["name"])    # Jordan
print(student["major"])   # Computer Science

In that example, "name", "age", and "major" are the keys. "Jordan", 22, and "Computer Science" are the values. You access each value by providing its key in square brackets. There is no position number involved.

Why the name "dictionary"?

The name comes from the real-world analogy: just as a physical dictionary maps words to definitions, a Python dictionary maps keys to values. Other programming languages call the same concept a hash map, associative array, or hash table.

Dictionaries exist because numbered positions are not always the right way to think about data. When you store a user profile, you do not care that the email is at index 2. You care that there is a field called "email" and you can grab it by name. That is exactly what a dictionary provides.

code builderclick a token to place it

Build a dictionary that maps the key "language" to the value "Python":

your code will appear here...
: [ settings } "Python" = ] { "language" config

Dictionaries vs. Lists: When to Choose Which

Lists and dictionaries are both built into Python, but they solve different problems. A list is a sequence of items accessed by their position (index 0, index 1, index 2, and so on). A dictionary is a collection of items accessed by a descriptive key. The choice between them depends on how you plan to find and use the data.

Imagine you are building a contact book. With a list, you would store names at even indexes and phone numbers at odd indexes, or maintain two parallel lists. Either approach is fragile. If you insert or remove an entry, you must keep both lists perfectly synchronized. With a dictionary, each name maps directly to its phone number. Adding and removing contacts is straightforward because the relationship is built into the structure itself.

python
# The list approach — fragile and error-prone
names  = ["Alice", "Bob", "Carol"]
phones = ["555-1234", "555-5678", "555-9012"]

# Finding Bob's phone requires scanning the names list first
index = names.index("Bob")
print(phones[index])          # 555-5678

# The dictionary approach — clean and direct
contacts = {
    "Alice": "555-1234",
    "Bob":   "555-5678",
    "Carol": "555-9012"
}

print(contacts["Bob"])        # 555-5678
List
By numeric index (position). You need to know where the item sits.
Dictionary
By a descriptive key. You need to know what the item is called.
List
O(n) for membership checks. Python scans the entire list to find a match.
Dictionary
O(1) average case. Python jumps straight to the value through hashing.
List
Allows duplicate values at different positions.
Dictionary
Keys must be unique. Assigning to an existing key overwrites the old value.
List
Ordered sequences where position matters, such as a ranked leaderboard or a queue of tasks.
Dictionary
Named data where you look things up by label, such as user profiles, configuration settings, or word frequency counts.
Rule of thumb

If you catch yourself writing two parallel lists where one holds labels and the other holds values, stop and use a dictionary instead. The code will be shorter, clearer, and faster.

spot the bugclick the line that contains the bug

This code tries to create a dictionary and print a value, but one line will crash. Find the bug.

1user = {
2 "name": "Jordan",
3 "role": "admin"
4}
5print(user["email"])
The fix: The key "email" does not exist in the dictionary. Accessing a missing key with bracket notation raises a KeyError. Use user.get("email", "not set") to return a default value instead of crashing.

How Dictionary Lookups Stay Fast

The reason dictionaries can find any value so quickly comes down to how they are built internally. Python dictionaries use a data structure called a hash table. When you add a key to a dictionary, Python runs the key through a hash function that converts it into a numeric address. That address tells Python exactly where to store the value in memory. When you later ask for that key, Python runs the same hash function again, gets the same address, and jumps straight to the stored value.

This is fundamentally different from how a list handles a search. When you write "Bob" in names_list, Python has to start at the beginning and check every single item until it finds a match or reaches the end. That process is called a linear scan, and it gets slower as the list grows. A list with ten thousand entries takes roughly ten thousand times longer to scan than a list with one entry.

With a dictionary, "Bob" in contacts_dict runs the hash function on "Bob", calculates the memory address, and checks that one location. Whether the dictionary holds ten items or ten million, the lookup takes roughly the same amount of time. This is what computer scientists call O(1) average-case time complexity.

python
# Checking membership: list vs dictionary
huge_list = list(range(1_000_000))
huge_dict = {i: True for i in range(1_000_000)}

# List: Python scans up to 1 million items — O(n)
999_999 in huge_list      # slow for large lists

# Dictionary: Python hashes the key and checks one spot — O(1)
999_999 in huge_dict      # fast regardless of size
Hash collisions

In rare cases, two different keys can produce the same hash value. Python handles this through a probing strategy that checks nearby slots. Worst case, this can slow a single lookup to O(n), but Python's hash function is designed to make collisions uncommon in normal use.

LIST SCAN vs DICTIONARY HASH LOOKUP List: O(n) linear scan [0] Alice [1] Bob [2] Carol ... checks each item one by one Dict: O(1) hash jump key hash() value jumps directly to the address 10,000 items = ~10,000 checks 1,000,000 items = ~1,000,000 checks gets slower as data grows 10,000 items = ~1 check 1,000,000 items = ~1 check stays fast as data grows
List membership checks scale linearly with size. Dictionary lookups stay constant thanks to hashing.

How to Create and Use a Dictionary in Python

Follow these four steps to start using dictionaries in your own code. Each step builds on the previous one.

  1. Create an empty dictionary

    Start with my_dict = {} or my_dict = dict(). Both produce the same empty dictionary. Use curly braces when you want concise syntax and the dict() constructor when you prefer explicit readability.

  2. Add key-value pairs

    Assign values to keys using bracket notation: my_dict["name"] = "Alice". Each assignment either adds a new key or updates an existing one. You can also create a dictionary with initial data: my_dict = {"name": "Alice", "age": 30}.

  3. Retrieve values safely with get()

    Use my_dict.get("name", "Unknown") to return "Unknown" if the key is missing. This avoids the KeyError you would get from my_dict["name"] when the key does not exist.

  4. Check for key existence

    Write if "name" in my_dict: to test whether a key is present. This is the fastest approach because it checks the hash table directly. Avoid writing "name" in my_dict.keys() since the in keyword already operates on the dictionary's keys by default.

python
# Putting all four steps together
profile = {}                          # Step 1: create
profile["name"] = "Jordan"            # Step 2: add
profile["email"] = "jordan@example.com"

# Step 3: safe retrieval
phone = profile.get("phone", "not provided")
print(phone)                          # not provided

# Step 4: check before acting
if "email" in profile:
    print(f"Contact: {profile['email']}")
else:
    print("No email on file")
"It is best to think of a dictionary as a set of key: value pairs." — Python Documentation

Beginner Learning Summary

  1. Dictionaries store data as key-value pairs, letting you retrieve values by a meaningful name instead of a position number.
  2. Use a dictionary when your data has a natural label-to-value relationship. Use a list when order and position are what matter.
  3. Dictionary lookups run in O(1) average time because Python hashes the key to find the memory address directly, while list membership checks run in O(n) time.
  4. Keys must be immutable types like strings, numbers, or tuples of immutable elements. Values can be anything.
  5. Use get() instead of bracket notation when a key might be missing, and use the in keyword to check whether a key exists before accessing it.

Dictionaries are one of the first tools that separate beginner Python code from solid Python code. Once you start reaching for them naturally, you will find that your programs become shorter, easier to read, and faster. Practice creating dictionaries from real scenarios: a phone book, a settings file, a word counter. The more you use them, the more intuitive they become.

check your understandingquestion 1 of 5

Frequently Asked Questions

A Python dictionary is a built-in data structure that stores data as key-value pairs inside curly braces. Each key maps to a value, and you retrieve values by referencing their key rather than a numeric index.

Use a dictionary when you need to look up values by a meaningful label rather than a position number. Dictionaries provide O(1) average-case lookups, meaning they find values in constant time regardless of size.

Dictionary keys must be immutable and hashable. This includes strings, numbers, and tuples that contain only immutable elements. Lists and other dictionaries cannot be used as keys because they are mutable.

Yes. Since Python 3.7, dictionaries officially maintain insertion order. Items come back in the order they were added. In Python 3.6, this was an implementation detail of CPython but not guaranteed by the language specification.

Dictionary lookups run in O(1) average-case time because Python implements dictionaries using a hash table. The hash function converts the key into a memory location for direct access, so lookup speed does not increase as the dictionary grows.

Using bracket notation on a missing key raises a KeyError. To avoid this, use the get() method, which returns None or a default value you specify when the key is not found.

Yes. Dictionary values can be any Python object, including strings, numbers, lists, other dictionaries, or even functions. There are no restrictions on value types.

Use the in keyword directly on the dictionary, such as: if 'name' in my_dict. This is the fastest approach because it checks the hash table directly in O(1) time.

dict[key] raises a KeyError if the key does not exist. dict.get(key) returns None by default when the key is missing, or a custom fallback value if you provide one as a second argument, such as dict.get(key, 'default').

As soon as your data has a natural label-to-value relationship. If you find yourself writing parallel lists where one holds names and the other holds values, that is a clear signal to switch to a dictionary.