← Back to course

Dictionaries: Keys and Values

Dictionaries: Keys and Values

Welcome back.

In the previous lesson, you learned lists.

Your programs learned how to store many values in one variable.

You wrote things like:

products = ["Keyboard", "Mouse", "Notebook"]

Very good.

Lists are useful when you need many values.

But sometimes a list is not enough.

Look at this:

user = ["Anna", 25, "Rome"]

This works.

But what does it mean?

Anna is probably the name.
25 is probably the age.
Rome is probably the city.

Probably.

And “probably” is not a good database design strategy.

Or a good life strategy.

Mostly.

A better way is to store data with names.

Like this:

user = {
    "name": "Anna",
    "age": 25,
    "city": "Rome"
}

Now the data is clear.

"name" points to "Anna".

"age" points to 25.

"city" points to "Rome".

This is a dictionary.

Dictionaries are very important in Python.

Very useful.

Very common.

Very close to how real data works in APIs, JSON, databases, settings, users, products, orders, and many other things.

In other words:

Welcome to structured data.

Very fancy.

Very practical.

Very Python.

What You Will Learn

In this lesson, you will learn:

By the end of this lesson, your programs will be able to work with structured data.

That is a huge step.

Because real applications are full of structured data.

Users have names.

Products have prices.

Orders have totals.

Tasks have statuses.

Blog posts have titles.

And every boss has “one small change”.

Also structured.

Also dangerous.

What Is a Dictionary?

A dictionary stores data as key-value pairs.

Example:

user = {
    "name": "Anna",
    "age": 25,
    "city": "Rome"
}

This dictionary has three keys:

name
age
city

And three values:

Anna
25
Rome

The key is like a label.

The value is the data.

So:

"name": "Anna"

means:

The key "name" has the value "Anna".

A dictionary uses curly braces:

{}

Each item has:

key: value

Items are separated by commas.

A dictionary is like a small information card.

Very organized.

Very useful.

Less likely to forget what user[1] means.

That is progress.

Your First Dictionary

Create a file:

dictionaries.py

Write:

user = {
    "name": "Anna",
    "age": 25,
    "city": "Rome"
}

print(user)

Run it:

python dictionaries.py

or:

python3 dictionaries.py

Output:

{'name': 'Anna', 'age': 25, 'city': 'Rome'}

Python prints the whole dictionary.

Notice:

curly braces
keys
values
colons
commas

That is the dictionary structure.

It may look a little heavier than a list.

But it is much clearer for structured data.

A list says:

Here are values.
Good luck.

A dictionary says:

Here are values with labels.
You are welcome.

Very polite.

Very Python.

Keys and Values

Look again:

user = {
    "name": "Anna",
    "age": 25,
    "city": "Rome"
}

Keys:

"name"
"age"
"city"

Values:

"Anna"
25
"Rome"

Each key points to one value.

You can think of it like this:

name -> Anna
age  -> 25
city -> Rome

This is why dictionaries are great for data that has meaning.

Example product:

product = {
    "name": "Keyboard",
    "price": 70.00,
    "available": True
}

Now we know what each value means.

No guessing.

No mysterious index numbers.

No “wait, was position 2 the price or the city?”

Beautiful.

Accessing Values by Key

To access a value, use the key inside square brackets.

Example:

user = {
    "name": "Anna",
    "age": 25,
    "city": "Rome"
}

print(user["name"])
print(user["age"])
print(user["city"])

Output:

Anna
25
Rome

This is very important.

With lists, you access by index:

products[0]

With dictionaries, you access by key:

user["name"]

The key tells Python which value you want.

Very readable.

Very useful.

Very “finally, the code explains itself”.

Dictionary Keys Are Exact

Keys must match exactly.

Example:

user = {
    "name": "Anna",
    "age": 25
}

print(user["name"])

Output:

Anna

But this is wrong:

print(user["Name"])

Python gives an error:

KeyError

Why?

Because "Name" and "name" are different keys.

Capital letters matter.

Spaces matter.

Everything matters.

Python does not guess.

Python is not your aunt trying to remember your password.

It needs the exact key.

Very strict.

Very useful.

Sometimes annoying.

Updating Values

You can change a value by assigning a new value to an existing key.

Example:

user = {
    "name": "Anna",
    "age": 25,
    "city": "Rome"
}

user["age"] = 26

print(user)

Output:

{'name': 'Anna', 'age': 26, 'city': 'Rome'}

We changed:

age from 25 to 26

This is very common.

Example:

product = {
    "name": "Keyboard",
    "price": 70.00
}

product["price"] = 65.00

print(product)

Output:

{'name': 'Keyboard', 'price': 65.0}

The product price changed.

The shop is happy.

The customer is happy.

The accountant is suspicious.

Normal.

Adding New Key-Value Pairs

You can add a new key-value pair by assigning a value to a new key.

Example:

user = {
    "name": "Anna",
    "age": 25
}

user["city"] = "Rome"

print(user)

Output:

{'name': 'Anna', 'age': 25, 'city': 'Rome'}

Before, the dictionary had:

name
age

After, it also has:

city

This is useful when you build data step by step.

Example:

product = {}

product["name"] = "Mouse"
product["price"] = 25.00
product["available"] = True

print(product)

Output:

{'name': 'Mouse', 'price': 25.0, 'available': True}

An empty dictionary starts like this:

product = {}

Then you can add data later.

Like a form.

But less annoying.

Removing Items with del

You can remove a key-value pair with del.

Example:

user = {
    "name": "Anna",
    "age": 25,
    "city": "Rome"
}

del user["city"]

print(user)

Output:

{'name': 'Anna', 'age': 25}

The key "city" and its value were removed.

Important:

del user["city"]

removes the whole key-value pair.

Not just the value.

The key disappears too.

Very direct.

Very powerful.

Use carefully.

del does not ask:

Are you sure?

Python trusts you.

Which is brave.

Maybe too brave.

Removing Items with pop()

You can also remove an item with pop().

Example:

user = {
    "name": "Anna",
    "age": 25,
    "city": "Rome"
}

city = user.pop("city")

print(city)
print(user)

Output:

Rome
{'name': 'Anna', 'age': 25}

pop() removes the item and gives you the removed value.

So this:

city = user.pop("city")

means:

Remove "city" from the dictionary and save its value in city.

This is useful when you still need the removed value.

del removes.

pop() removes and returns.

Small difference.

Big usefulness.

Checking If a Key Exists

Use in to check if a key exists in a dictionary.

Example:

user = {
    "name": "Anna",
    "age": 25
}

if "name" in user:
    print("Name exists.")
else:
    print("Name is missing.")

Output:

Name exists.

Important:

"name" in user

checks keys.

Not values.

Example:

user = {
    "name": "Anna",
    "age": 25
}

print("Anna" in user)

Output:

False

Why?

Because "Anna" is a value, not a key.

The keys are:

name
age

This is a common beginner confusion.

When using in with a dictionary, Python checks keys by default.

Very important.

Tattoo it on your debugging brain.

Maybe not literally.

Avoiding KeyError with get()

If you access a missing key with square brackets, Python gives KeyError.

Example:

user = {
    "name": "Anna",
    "age": 25
}

print(user["city"])

Error:

KeyError

Because "city" does not exist.

A safer way is get().

Example:

user = {
    "name": "Anna",
    "age": 25
}

print(user.get("city"))

Output:

None

None means:

No value

You can also provide a default value:

print(user.get("city", "Unknown"))

Output:

Unknown

This is very useful.

get() helps avoid errors when a key may be missing.

Very practical.

Very real-world.

Because real-world data is often incomplete.

Like forms.

And people.

Square Brackets vs get()

Both can access values.

Example:

user = {
    "name": "Anna"
}

print(user["name"])
print(user.get("name"))

Output:

Anna
Anna

Difference:

user["city"]

gives an error if "city" does not exist.

But:

user.get("city")

returns None.

And:

user.get("city", "Unknown")

returns "Unknown".

Simple rule:

Use [] when the key must exist.
Use get() when the key may be missing.

This is not just beginner advice.

This is real programming advice.

The kind that saves you from bugs that appear only on Friday evening.

The worst kind.

Looping Through Dictionary Keys

You can loop through a dictionary.

Example:

user = {
    "name": "Anna",
    "age": 25,
    "city": "Rome"
}

for key in user:
    print(key)

Output:

name
age
city

By default, looping through a dictionary gives keys.

This:

for key in user:

means:

For each key in the dictionary...

You can then access the value:

for key in user:
    print(user[key])

Output:

Anna
25
Rome

Very useful.

Keys open the doors.

Values are behind the doors.

Dictionaries are tiny hotels.

Apparently.

Looping Through Keys and Values

A nicer way is to use .items().

Example:

user = {
    "name": "Anna",
    "age": 25,
    "city": "Rome"
}

for key, value in user.items():
    print(f"{key}: {value}")

Output:

name: Anna
age: 25
city: Rome

This is very common.

.items() gives both key and value.

The loop:

for key, value in user.items():

means:

For each key-value pair in the dictionary...

This is one of the most important dictionary patterns.

Learn it well.

It will come back.

Like semicolons in SQL.

But kinder.

Looping Through Only Values

You can use .values() if you only want values.

Example:

user = {
    "name": "Anna",
    "age": 25,
    "city": "Rome"
}

for value in user.values():
    print(value)

Output:

Anna
25
Rome

You can use .keys() if you only want keys:

for key in user.keys():
    print(key)

Output:

name
age
city

But remember:

for key in user:

already loops through keys.

So .keys() is optional most of the time.

Python gives choices.

Choices are nice.

Until you have too many.

Then welcome to programming.

Dictionary with User Input

Create a file:

user_profile.py

Write:

user = {}

user["name"] = input("Name: ")
user["age"] = int(input("Age: "))
user["city"] = input("City: ")

print("User profile:")

for key, value in user.items():
    print(f"{key}: {value}")

Example:

Name: Anna
Age: 25
City: Rome

Output:

User profile:
name: Anna
age: 25
city: Rome

This program builds a dictionary from user input.

The keys are fixed.

The values come from the user.

This is very close to real forms.

A user fills fields.

The program stores structured data.

Very real.

Very useful.

Very “this could become a web form later”.

Dangerous thought.

Product Dictionary

Create a product dictionary:

product = {
    "name": "Keyboard",
    "price": 70.00,
    "available": True
}

print(f"Product: {product['name']}")
print(f"Price: {product['price']:.2f}")

if product["available"]:
    print("Available")
else:
    print("Not available")

Output:

Product: Keyboard
Price: 70.00
Available

This is a very common idea.

Products have:

name
price
availability

Users have:

name
email
age
city

Tasks have:

title
status
priority

Dictionaries are perfect for this.

They give meaning to data.

Meaning is good.

Without meaning, you are just staring at numbers and hoping.

That is not engineering.

That is astrology with extra steps.

Lists of Dictionaries

Now things become more interesting.

You can store dictionaries inside a list.

Example:

products = [
    {"name": "Keyboard", "price": 70.00},
    {"name": "Mouse", "price": 25.00},
    {"name": "Notebook", "price": 5.50}
]

This is a list.

Inside the list, each item is a dictionary.

This is very common in real applications.

Why?

Because you often have many structured objects.

Many products.

Many users.

Many orders.

Many tasks.

A list stores many items.

A dictionary describes each item.

Together they are powerful.

Very powerful.

Very normal.

Very close to JSON and APIs.

The backend is smiling.

Looping Through a List of Dictionaries

Example:

products = [
    {"name": "Keyboard", "price": 70.00},
    {"name": "Mouse", "price": 25.00},
    {"name": "Notebook", "price": 5.50}
]

for product in products:
    print(f"{product['name']}: {product['price']:.2f}")

Output:

Keyboard: 70.00
Mouse: 25.00
Notebook: 5.50

What happens?

products is a list.
Each product is a dictionary.
The loop takes one dictionary at a time.
Then we read product["name"] and product["price"].

This pattern is everywhere.

If you work with APIs, you will see this constantly.

A response often looks like:

list of dictionaries

Or in JSON language:

array of objects

Same idea.

Different clothes.

Calculating Total from List of Dictionaries

You can calculate a total.

Example:

products = [
    {"name": "Keyboard", "price": 70.00},
    {"name": "Mouse", "price": 25.00},
    {"name": "Notebook", "price": 5.50}
]

total = 0

for product in products:
    total += product["price"]

print(f"Total: {total:.2f}")

Output:

Total: 100.50

This combines:

list
dictionary
loop
number
total

Very strong.

Very realistic.

Many real systems do this.

Shopping carts.

Invoices.

Order summaries.

Reports.

And then taxes.

Again.

The tax monster never sleeps.

Dictionaries with Lists Inside

A dictionary can also contain a list.

Example:

course = {
    "title": "Python Course",
    "lessons": ["Variables", "Input", "Conditions", "Loops", "Lists"]
}

print(course["title"])

for lesson in course["lessons"]:
    print(f"- {lesson}")

Output:

Python Course
- Variables
- Input
- Conditions
- Loops
- Lists

Here:

course["lessons"]

is a list.

This is very useful when one object has many related values.

Example:

user with many skills
course with many lessons
order with many products
blog post with many tags

Dictionaries and lists work together beautifully.

Like pasta and sauce.

But with more brackets.

Nested Dictionaries

A dictionary can contain another dictionary.

Example:

user = {
    "name": "Anna",
    "address": {
        "city": "Rome",
        "country": "Italy"
    }
}

print(user["name"])
print(user["address"]["city"])
print(user["address"]["country"])

Output:

Anna
Rome
Italy

This is called nested data.

Nested means:

inside another thing

Here:

user["address"]

is another dictionary.

Then:

user["address"]["city"]

gets the city inside the address dictionary.

This looks a little scary at first.

But it is just:

open user
open address
read city

Like opening boxes.

Please do not put too many boxes inside boxes.

That way madness lives.

And JSON.

Common Mistake: Missing Quotes Around Keys

Wrong:

user = {
    name: "Anna",
    age: 25
}

Python thinks name and age are variable names.

But they are not defined.

Correct:

user = {
    "name": "Anna",
    "age": 25
}

String keys need quotes.

This is a very common beginner mistake.

Remember:

"name" is text
name is a variable

Different things.

Tiny quotes.

Big difference.

Classic programming drama.

Common Mistake: Using = Instead of :

Wrong:

user = {
    "name" = "Anna",
    "age" = 25
}

Correct:

user = {
    "name": "Anna",
    "age": 25
}

Inside dictionaries, use colon:

"key": value

Not equals.

The equals sign is for assignment:

user = {}

The colon is for key-value pairs:

"name": "Anna"

Python is very specific.

Like an accountant with syntax rules.

Common Mistake: Missing Commas

Wrong:

user = {
    "name": "Anna"
    "age": 25
}

Correct:

user = {
    "name": "Anna",
    "age": 25
}

Dictionary items need commas between them.

Without commas, Python gets confused.

And when Python gets confused, it gives errors.

At least it does not shout.

Usually.

Common Mistake: KeyError

Wrong:

user = {
    "name": "Anna"
}

print(user["city"])

This gives:

KeyError

Because "city" does not exist.

Safer:

print(user.get("city", "Unknown"))

Output:

Unknown

Use get() when the key may be missing.

This is very important when working with real data.

Real data is often incomplete.

Because humans fill forms.

And humans are creative.

In bad ways.

Common Mistake: Confusing List Indexes and Dictionary Keys

List:

products = ["Keyboard", "Mouse"]

Access with index:

products[0]

Dictionary:

product = {
    "name": "Keyboard",
    "price": 70.00
}

Access with key:

product["name"]

Do not write:

product[0]

That is not how this dictionary works.

Lists use positions.

Dictionaries use keys.

Simple rule:

list        index
dictionary  key

Very important.

Very easy to mix at first.

Very normal.

Mini Program: User Card

Create a file:

user_card.py

Write:

user = {
    "name": input("Name: "),
    "age": int(input("Age: ")),
    "city": input("City: ")
}

print("----- User Card -----")
print(f"Name: {user['name']}")
print(f"Age: {user['age']}")
print(f"City: {user['city']}")

Example:

Name: Anna
Age: 25
City: Rome

Output:

----- User Card -----
Name: Anna
Age: 25
City: Rome

This is simple but important.

You collect data.

You store it in a dictionary.

You print it nicely.

This is the beginning of structured user data.

Very useful.

Very real.

Mini Program: Product Manager

Create a file:

product_manager.py

Write:

product = {}

product["name"] = input("Product name: ")
product["price"] = float(input("Price: "))
product["available"] = input("Available? yes/no: ").lower() == "yes"

print("----- Product -----")
print(f"Name: {product['name']}")
print(f"Price: {product['price']:.2f}")

if product["available"]:
    print("Status: available")
else:
    print("Status: not available")

Example:

Product name: Keyboard
Price: 70
Available? yes/no: yes

Output:

----- Product -----
Name: Keyboard
Price: 70.00
Status: available

This program uses:

Very good practice.

And yes, this is starting to look like product data in a shop.

Small shop.

Small Python.

Big future.

Mini Program: Product List

Create a file:

product_list_dictionaries.py

Write:

products = []

product_count = int(input("How many products? "))

for number in range(1, product_count + 1):
    print(f"Product {number}")

    product = {
        "name": input("Name: "),
        "price": float(input("Price: "))
    }

    products.append(product)

print("----- Products -----")

for product in products:
    print(f"{product['name']}: {product['price']:.2f}")

Example:

How many products? 2
Product 1
Name: Keyboard
Price: 70
Product 2
Name: Mouse
Price: 25

Output:

----- Products -----
Keyboard: 70.00
Mouse: 25.00

This is powerful.

You are building a list of dictionaries.

That is a very real data structure.

It is not just beginner practice.

It is how many real programs organize data.

Very strong step.

Practice

Create a file:

practice_dictionaries.py

Write a program that:

Example solution:

book = {}

book["title"] = input("Title: ")
book["author"] = input("Author: ")
book["year"] = int(input("Year: "))

print("----- Book -----")

for key, value in book.items():
    print(f"{key}: {value}")

if book["year"] < 2000:
    print("This book was published before 2000.")
else:
    print("This book was published in 2000 or later.")

This program combines:

Very useful.

Very clean.

Very structured.

Like a tiny library system.

Without late fees.

For now.

Mini Challenge

Create a file:

contact_book.py

Your program should:

Each contact should be a dictionary with:

name
email
phone

Menu:

1. Add contact
2. Show contacts
q. Quit

Example solution:

contacts = []

while True:
    print("----- Contact Book -----")
    print("1. Add contact")
    print("2. Show contacts")
    print("q. Quit")

    choice = input("Choose an option: ").lower()

    if choice == "1":
        contact = {
            "name": input("Name: "),
            "email": input("Email: "),
            "phone": input("Phone: ")
        }

        contacts.append(contact)
        print("Contact added.")
    elif choice == "2":
        if len(contacts) == 0:
            print("No contacts yet.")
        else:
            print("Contacts:")

            for contact in contacts:
                print("-----")
                print(f"Name: {contact['name']}")
                print(f"Email: {contact['email']}")
                print(f"Phone: {contact['phone']}")
    elif choice == "q":
        print("Goodbye.")
        break
    else:
        print("Unknown option.")

This is a real mini application.

It uses:

This is a serious beginner project.

Small, yes.

But serious.

A contact book is real software logic.

You are no longer just printing “Hello”.

You are storing structured data.

Respect.

Very Python respect.

Extra Challenge: Search Contacts

Improve contact_book.py.

Add a menu option:

3. Search contact

Ask the user for a name.

Then search contacts by name.

Example idea:

elif choice == "3":
    search_name = input("Name to search: ")

    found = False

    for contact in contacts:
        if contact["name"] == search_name:
            print("Contact found:")
            print(f"Name: {contact['name']}")
            print(f"Email: {contact['email']}")
            print(f"Phone: {contact['phone']}")
            found = True

    if not found:
        print("Contact not found.")

This adds:

Very useful.

Very real.

This is how many simple data systems begin.

Add data.

Show data.

Search data.

Then one day someone says:

Can we save it to a database?

And PostgreSQL enters the room wearing sunglasses.

Beginner Checklist

When your dictionary program does not work, check:

Did I use curly braces?
Did I use "key": value?
Did I separate items with commas?
Did I put string keys in quotes?
Did I use : inside the dictionary, not =?
Does the key exist?
Did I spell the key correctly?
Did I use the same capital letters?
Should I use get() instead of []?
Am I confusing list indexes with dictionary keys?
Am I looping through keys, values, or items?

Dictionaries are powerful.

But key names must be exact.

Most beginner dictionary bugs are caused by:

wrong key
missing key
missing quotes
missing comma
using = instead of :

The good news:

These errors are normal.

The better news:

They become easier to spot.

The bad news:

You will still make them.

Welcome to programming.

Summary

Today you learned:

This is a huge step.

Now your programs can store meaningful data.

Not just values.

Labeled values.

Structured values.

Data that looks like real application data.

Users.

Products.

Contacts.

Books.

Tasks.

Orders.

Profiles.

You are getting much closer to real software.

Very strong progress.

Very Python.

Next Lesson

In the next lesson, we will learn functions.

Functions let you reuse code.

Instead of writing the same logic again and again, you will create your own commands.

Like this:

def greet_user(name):
    print(f"Hello, {name}!")

Then you can call:

greet_user("Anna")
greet_user("Marco")
greet_user("Sofia")

Functions are one of the biggest steps in programming.

They help you organize code.

They reduce repetition.

They make programs easier to read.

And they make your code look less like spaghetti.

Very important.

Very Python.

Very next level.