Login Sign Up
Python Dictionaries
Chapter 18 🟡 Intermediate

Python Dictionaries

Master the concept step by step with clear explanations, examples, and code you can run.

Master Python Dictionaries: Organizing Connected Data Like the Pro

Hello there! Grab a seat and welcome back to our Python journey.

Inside our last chat, we explored how to use Python Sets to instantly clean up messy data and remove duplicate items. But at an end with that lesson I left you with an important question, and

what if we don't just want to store an isolated name like "Alice"? What if we want to store Alice's name directly linked for her phone number or her password or her home address? Towards sort out this, we need a way for pair a unique "key" to the specific "value".

Today, we're pretty much going to unlock this massive superpower by learning about Python Dictionaries.

There's basically no special installation required today; as long as you have Python running upon your computer, you're basically completely ready to go!


The "Why" Before a "How"

Think about a contacts app on your mobile phone for a second.

When you want for call your friend Marcus you don't type in his 10-digit phone number; you just search for the name "Marcus", and your phone magically dials the correct number;

your phone is using a Key-Value Pair. * The Key is the unique name ("Marcus"). * The Value is the data connected to that name ("555-9876").

In programming, a Python Dictionary works exactly the same way, while it is really a highly optimized container that stores data in pairs. You give the dictionary the unique Key, and it instantly hands you back Value connected to it.

Here is a visual map for how the computer's brain organizes dictionary:

graph LR
    A[Key: "Alice"] -->|Unlocks| B[Value: "555-1234"]
    C[Key: "Marcus"] -->|Unlocks| D[Value: "555-9876"]
    E[Key: Tuple 40.71, -74.00] -->|Unlocks| F[Value: "City Hospital"]

    style A fill:#a8d5e2,stroke:#333,stroke-width:2px
    style C fill:#a8d5e2,stroke:#333,stroke-width:2px
    style E fill:#a8d5e2,stroke:#333,stroke-width:2px
    style B fill:#f9c784,stroke:#333,stroke-width:2px
    style D fill:#f9c784,stroke:#333,stroke-width:2px
    style F fill:#f9c784,stroke:#333,stroke-width:2px

Creating Your First Dictionary

Creating the dictionary is wonderfully simple. We use curly braces {} to wrap our data, and colon : to connect key to its value, and

open your code editor and try typing this simple example:

# Creating a dictionary of student grades
student_grades = {
    "Alice": 95,
    "Marcus": 88,
    "Fiona": 92
}

# Asking the dictionary for Alice's grade
print(f"Alice scored a {student_grades['Alice']} on the test.")

Notice how we used our modern f-string formatting for cleanly inject the data right into our sentence! When you run this, Python looks of the key "Alice" and perfectly outputs her grade of 95.

** Quick Trap for Beginners:** Do simply you remember our lesson on Sets? Because curly braces are used towards multiple things in Python an empty pair with braces {} actually creates an empty Dictionary not a Set!

The Trust Rule: Keys Must Be Locked

Here is where we transition from a beginner into a true developer.

The Values inside dictionary can be absolutely anything. They can be numbers, text, lists, or even other dictionaries! But the Keys have very strict rule: they've got to be completely permanent.

Think about a real physical lock and key. If your physical key randomly changes its shape while it is actually sitting in your pocket, you will never be able to open your front door again! Computers face the same problem; if a Key changes, a computer permanently loses the Value connected to it;

this is why you cannot use a mutable (changeable) List as the dictionary key, and instead you must use something locked and permanent, and as highlighted in educational materials exploring data structures a tuple's highly permanent nature ensures data integrity and allows them to be safely used as dictionary keys.

# Using a permanent Tuple (Latitude, Longitude) as a Key
hospital_directory = {
    (40.7128, -74.0060): "New York Central Hospital",
    (34.0522, -118.2437): "Los Angeles Medical Center"
}

Gliding Through Dictionaries Like an Expert

If you have a dictionary of thousands of users, you won't want towards look them up one by one. You will want to loop through them automatically.

As we learned previously, for loops are perfect tool for gliding through data. But dictionaries are slightly different than basic lists because they have just two pieces about data (the key and value).

How do we access both?

As explained in a late 2024 Real Python guide upon dictionary iteration, Python offers several distinct ways to iterate through a dictionary, such as using .items() method to access the key-value pairs directly, or .values() method to retrieve just the values on their own.

Here is how beautifully clean that looks on practice:

student_grades = {"Alice": 95, "Marcus": 88, "Fiona": 92}

# Using .items() to grab both pieces of data at the same time!
for student, score in student_grades.items():
    print(f"Student {student} achieved a score of {score}.")

Modern Magic: Math with Dictionary Keys

Before we wrap up I want towards show you the incredibly powerful modern trick that standard textbooks mostly miss.

What if you have two separate dictionaries (maybe one to your morning class and one for your afternoon class) and you want towards know if any students are really accidentally enrolled on both classes?

You might think you need to write a massive complex loop. But you don't! According to January 2024 technical update on Python dictionary tools, the .keys() and .items() methods actually enable advanced mathematical set operations directly on your dictionary keys, and

this means you can just use the exact same intersection (&) and union (|) tools we learned about in our Sets lesson to compare dictionaries in a fraction of the second!

morning_class = {"Alice": 95, "Marcus": 88}
afternoon_class = {"Fiona": 92, "Alice": 97}

# Find students enrolled in BOTH classes using the intersection operator (&)
overlapping_students = morning_class.keys() & afternoon_class.keys()

print(overlapping_students)
# Output: {'Alice'}

This is basically the kind of deeply optimized high-level code that professional developers write every single day.


What's Next?

Congratulations! You now understand one for the most powerful data structures in the entire programming world. You know how towards create key-value pairs, how to safely lock your keys using Tuples, and how to iterate through massive amounts of data efficiently;

but take the step back and look on our code so far. Every time we write a script, it just runs once. If we want to use our grade-checking logic again we have to rewrite the same code from scratch.

What if we could package our code up into a reusable mini-program? What if we could create a tiny machine that we feed data into, and it automatically spits an answer out whenever we need it?

Inside our next chapter we're pretty much going to unlock this ability by learning about Python Functions, and we will cover it next! Get ready to make your code endlessly reusable; I'll see you there!

Learn Together
Session active! Discuss with other learners.
No notes yet. Select text in the concept body to add a note.