DEV Community

Cover image for Dictionaries: When a List Just Isn't Enough
Akhilesh
Akhilesh

Posted on

Dictionaries: When a List Just Isn't Enough

You have a list of five numbers.

person = ["Alex", 25, "Mumbai", True, "alex@email.com"]
Enter fullscreen mode Exit fullscreen mode

Quick question. What is person[3]?

You have to count. Index 0 is the name. Index 1 is age. Index 2 is city. Index 3 is... the boolean? What does True mean here? Is that married? Is that a student? Is that something else entirely?

You wrote this code yourself and you already can't remember what index 3 means.

Now imagine coming back to this code three weeks later.


This is the exact problem dictionaries solve. Instead of accessing data by position, you access it by name. Instead of person[3] you write person["is_student"]. The name tells you everything.


What a Dictionary Looks Like

Curly braces. Key and value pairs separated by colons. Pairs separated by commas.

person = {
    "name": "Alex",
    "age": 25,
    "city": "Mumbai",
    "is_student": True,
    "email": "alex@email.com"
}
Enter fullscreen mode Exit fullscreen mode

Now access any value by its key.

print(person["name"])
print(person["age"])
print(person["is_student"])
Enter fullscreen mode Exit fullscreen mode

Output:

Alex
25
True
Enter fullscreen mode Exit fullscreen mode

No counting. No guessing. person["age"] tells you exactly what you're getting.


Adding, Changing, Removing

A dictionary is not frozen after you create it. You can change it freely.

person = {"name": "Alex", "age": 25}

person["city"] = "Mumbai"        # add new key
person["age"] = 26               # update existing key
del person["city"]               # delete a key

print(person)
Enter fullscreen mode Exit fullscreen mode

Output:

{'name': 'Alex', 'age': 26}
Enter fullscreen mode Exit fullscreen mode

Assigning to a key that exists updates it. Assigning to a key that doesn't exist creates it. Clean and consistent.


The Safe Way to Get Values

What happens when you ask for a key that doesn't exist?

person = {"name": "Alex", "age": 25}
print(person["city"])
Enter fullscreen mode Exit fullscreen mode
KeyError: 'city'
Enter fullscreen mode Exit fullscreen mode

Your program crashes. Not ideal.

Use .get() instead. It returns None if the key doesn't exist instead of crashing.

city = person.get("city")
print(city)                         # None

city = person.get("city", "Unknown")
print(city)                         # Unknown
Enter fullscreen mode Exit fullscreen mode

The second argument to .get() is a default value. If the key exists, you get the real value. If it doesn't, you get the default. Your program keeps running.

Use .get() whenever the key might not be there. Use person["key"] only when you're certain the key exists.


Looping Through a Dictionary

Three ways. Each one useful for different situations.

scores = {"Alex": 92, "Priya": 88, "Sam": 75, "Jordan": 95}

for key in scores:
    print(key)
Enter fullscreen mode Exit fullscreen mode

Output:

Alex
Priya
Sam
Jordan
Enter fullscreen mode Exit fullscreen mode

Just the keys. Now both:

for key, value in scores.items():
    print(f"{key}: {value}")
Enter fullscreen mode Exit fullscreen mode

Output:

Alex: 92
Priya: 88
Sam: 75
Jordan: 95
Enter fullscreen mode Exit fullscreen mode

.items() gives you each key-value pair as a tuple. The for key, value unpacks it. This is the one you'll use most.

Just the values if you need them:

for value in scores.values():
    print(value)
Enter fullscreen mode Exit fullscreen mode

Output:

92
88
75
95
Enter fullscreen mode Exit fullscreen mode

Checking If a Key Exists

Before you access a key, sometimes you need to know if it's there.

person = {"name": "Alex", "age": 25}

if "city" in person:
    print(person["city"])
else:
    print("No city found")
Enter fullscreen mode Exit fullscreen mode

Output:

No city found
Enter fullscreen mode Exit fullscreen mode

in works with dictionaries just like with lists. Checks keys, not values.


Dictionaries Inside Lists

This is the pattern you will see constantly in real data work.

students = [
    {"name": "Alex", "score": 92, "passed": True},
    {"name": "Priya", "score": 58, "passed": False},
    {"name": "Sam", "score": 75, "passed": True},
    {"name": "Jordan", "score": 44, "passed": False}
]

for student in students:
    if student["passed"]:
        print(f"{student['name']} passed with {student['score']}")
    else:
        print(f"{student['name']} needs to retake the exam")
Enter fullscreen mode Exit fullscreen mode

Output:

Alex passed with 92
Priya needs to retake the exam
Sam passed with 75
Jordan needs to retake the exam
Enter fullscreen mode Exit fullscreen mode

A list of dictionaries. Every item in the list is a dictionary with the same keys. This is exactly how JSON data looks. This is how APIs return data. This is how database records get processed in Python.

Get comfortable with this shape. You'll work with it for the rest of your programming life.


Counting Things With a Dictionary

One classic use case. Count how many times each item appears.

words = ["python", "is", "fun", "python", "is", "great", "python"]

counts = {}

for word in words:
    if word in counts:
        counts[word] = counts[word] + 1
    else:
        counts[word] = 1

print(counts)
Enter fullscreen mode Exit fullscreen mode

Output:

{'python': 3, 'is': 2, 'fun': 1, 'great': 1}
Enter fullscreen mode Exit fullscreen mode

Walk through what happens. First time Python sees "python", it's not in counts yet. So counts["python"] = 1. Second time it sees "python", it IS in counts. So counts["python"] = counts["python"] + 1 which is 1 + 1 = 2. Third time, 2 + 1 = 3.

This exact pattern, counting occurrences, shows up in text analysis, data cleaning, building histograms, and more.


The One Thing That Catches Everyone

Dictionary keys must be unique. If you add the same key twice, the second value overwrites the first. Silently. No error.

data = {
    "name": "Alex",
    "age": 25,
    "name": "Alexander"      # duplicate key
}

print(data["name"])
Enter fullscreen mode Exit fullscreen mode

Output:

Alexander
Enter fullscreen mode Exit fullscreen mode

"Alex" is gone. "Alexander" replaced it without any warning. Python doesn't complain. This causes bugs that are genuinely hard to find because nothing crashes.

Double check your keys when creating a dictionary manually.


Dictionary vs List: When to Use Which

Use a list when order matters and you're dealing with a sequence of similar things. A list of names. A list of scores. A sequence of steps.

Use a dictionary when you want to label your data. A user profile. A config file. Anything where you need to look something up by name instead of by position.

In data science and AI, you'll use both constantly, often together. Models output dictionaries. Datasets are lists of dictionaries. Configuration is a dictionary. Results are stored in dictionaries.


Try This

Create dictionaries_practice.py.

Build a dictionary for a product in an online store. It should have at least six keys: name, price, category, in_stock (boolean), rating, and number of reviews.

Then write code that does all of this:

Print a nicely formatted product description using the values from your dictionary.

Add a "discount_percent" key with a value of 10.

Calculate and print the discounted price using the values already in the dictionary.

Write a loop that goes through the dictionary and prints every key and value on its own line.

Finally, try accessing a key that doesn't exist using .get() with a sensible default value.


What's Next

Lists and dictionaries store collections of data. But what if you want to create your own custom data type, something that bundles both data and behavior together? That's what classes and objects are for, and that's exactly where we're heading.

Top comments (0)