Dev.to WebDev šŸ›  Dev šŸ‘ 0 šŸ“– 11 min read

Python Dictionaries: What I Learned About Key-Value Data

After working with lists and tuples, I came across dictionaries. At first, dictionaries felt a little strange because I was used to accessing things by position, like products[0]. With dictionaries, I had to use keys i

After working with lists and tuples, I came across dictionaries.

At first, dictionaries felt a little strange because I was used to accessing things by position, like products[0].

With dictionaries, I had to use keys instead.

That was the main idea I had to understand.

A dictionary stores information as key-value pairs.

Creating a dictionary

A dictionary uses curly brackets {}.

For example:

student = {"name": "Feddy", "age": 20, "course": "Data Science"}

Here:

"name" is the key.

"Feddy" is the value.

The same applies to the other pieces of information.

I started thinking of it as giving every piece of information a label.

Accessing values

Unlike a list, I don't use a position.

I use the key:

student = {"name": "Feddy", "age": 20, "course": "Data Science"}

print(student["name"])

The result is:

Feddy

I can also access the age:

print(student["age"])

The result is:

20

This was the point where dictionaries started making sense to me.

Instead of thinking, "Which position is the age in?", I just ask for "age".

Using get()

There is another way to access a value:

student.get("name")

This also gives:

Feddy

The difference becomes useful when the key doesn't exist.

For example:

print(student.get("phone"))

Instead of raising an error, Python returns:

None

I can even provide a default value:

print(student.get("phone", "No phone number"))

Now I get:

No phone number

I found this useful when working with data where some information might be missing.

Adding new values

Dictionaries are changeable.

I can add a new key-value pair like this:

student["city"] = "Nairobi"

Now the dictionary contains the city as well.

I don't have to recreate the entire dictionary just to add one more piece of information.

Updating values

I can also change an existing value.

For example:

student["age"] = 21

Now the age is 21.

The same syntax is used for both adding and updating.

If the key already exists, the value changes.

If it doesn't exist, Python adds it.

Removing values

There are a few ways to remove dictionary items.

Using pop():

student.pop("city")

This removes the "city" entry.

I can also use del:

del student["age"]

And if I want to remove everything:

student.clear()

The dictionary itself still exists, but there is nothing inside it.

Checking if a key exists

I can check whether a key is in a dictionary using in.

For example:

"name" in student

This returns:

True

I can also use it in a condition:

if "phone" in student:

print("Phone number exists")

This became useful when dealing with information that isn't always available.

Finding the number of items

Just like with lists and tuples, I can use len().

student = {"name": "Feddy", "age": 20, "course": "Data Science"}

print(len(student))

The result is:

3

There are three key-value pairs in the dictionary.

Getting all keys

I can get all the keys using keys():

student.keys()

For example:

for key in student.keys():

print(key)

This would give me:

name

age

course

I use this when I only care about the labels.

Getting all values

I can get the values using values():

for value in student.values():

print(value)

This gives:

Feddy

20

Data Science

Getting keys and values together

This is one of the dictionary methods I use most.

items() gives me both:

for key, value in student.items():

print(f"{key}: {value}")

The output would be:

name: Feddy

age: 20

course: Data Science

This is especially useful when I want to go through all the information in a dictionary.

Looping through dictionaries

I can loop through a dictionary in different ways.

Just the keys:

for key in student:

print(key)

Just the values:

for value in student.values():

print(value)

Or both:

for key, value in student.items():

print(key, value)

I found .items() easiest when I wanted to actually work with the information.

Dictionary with numbers

Dictionaries don't have to store text.

For example:

prices = {"Bread": 80, "Milk": 120, "Sugar": 180}

I can get the price of milk:

print(prices["Milk"])

The result is:

120

I can also update it:

prices["Milk"] = 130

Now the price is 130.

This made dictionaries feel useful for things like products and prices.

A practical inventory example

Let's say I'm building a small shop inventory.

I could have:

product = {"name": "Bread", "price": 80, "quantity": 20}

Now I can access each piece of information:

print(product["name"])

print(product["price"])

print(product["quantity"])

I can also calculate the value of the stock:

stock_value = product["price"] * product["quantity"]

print(stock_value)

The result is:

1600

Now the dictionary is storing information, while my code is using that information to do something useful.

Nested dictionaries

This is where dictionaries become much more powerful.

A dictionary can contain another dictionary.

For example:

students = {

"student1": {"name": "Feddy", "age": 20, "course": "Data Science"},

"student2": {"name": "Amina", "age": 21, "course": "Python"}

}

Now I can access Feddy's name using:

print(students["student1"]["name"])

The result is:

Feddy

And Amina's course:

print(students["student2"]["course"])

The result is:

Python

At first this looked confusing because there are multiple brackets, but I realised I was simply going one dictionary level at a time.

A list of dictionaries

I can also combine dictionaries with lists.

For example:

students = [

{"name": "Feddy", "age": 20},

{"name": "Amina", "age": 21},

{"name": "Brian", "age": 19}

]

Now I have a list containing three dictionaries.

I can loop through them:

for student in students:

print(student["name"])

This gives:

Feddy

Amina

Brian

This structure started making a lot of sense to me because it looks much more like real data.

Dictionary comprehension

Just like lists have comprehensions, dictionaries do too.

For example:

squares = {number: number ** 2 for number in range(1, 6)}

The result is:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

I found this easier to understand after becoming comfortable with normal loops.

The same idea is happening, but Python lets me write it in a shorter form.

Copying dictionaries

Just like lists, I need to be careful when copying dictionaries.

If I do:

student2 = student

both variables refer to the same dictionary.

So changing one can affect the other.

To create a separate copy, I can use:

student2 = student.copy()

Now I can modify student2 without changing the original dictionary.

What I understood about dictionaries

The biggest thing I learnt is that dictionaries are really useful when the information needs labels.

With a list, I might have:

student = ["Feddy", 20, "Data Science"]

But now I have to remember that index 0 is the name, index 1 is the age, and index 2 is the course.

With a dictionary:

student = {"name": "Feddy", "age": 20, "course": "Data Science"}

I don't have to remember positions.

I just use the key I need.

Lists vs dictionaries

This is how I now think about the difference.

A list:

products = ["Bread", "Milk", "Sugar"]

is useful when I mainly care about the collection of items.

A dictionary:

product = {"name": "Bread", "price": 80, "quantity": 20}

is useful when I care about different pieces of information about one thing.

And I can combine them:

inventory = [

{"name": "Bread", "price": 80, "quantity": 20},

{"name": "Milk", "price": 120, "quantity": 15},

{"name": "Sugar", "price": 180, "quantity": 10}

]

That combination is something I expect to use a lot as I build bigger Python programs.

Final thoughts

Dictionaries took some getting used to because they are different from the position-based approach I was used to with lists.

But once I understood the idea of keys and values, everything started falling into place.

I can add information, update it, remove it, search for it, loop through it, and even put dictionaries inside other data structures.

The biggest thing I took away is simple:

A list helps me organise items.

A dictionary helps me organise information about those items.

That distinction has made choosing between the two much easier for me.

After working with lists and tuples, I came across dictionaries.

At first, dictionaries felt a little strange because I was used to accessing things by position, like products[0].

With dictionaries, I had to use keys instead.

That was the main idea I had to understand.

A dictionary stores information as key-value pairs.

Creating a dictionary

A dictionary uses curly brackets {}.

For example:

student = {"name": "Feddy", "age": 20, "course": "Data Science"}

Here:

"name" is the key.

"Feddy" is the value.

The same applies to the other pieces of information.

I started thinking of it as giving every piece of information a label.

Accessing values

Unlike a list, I don't use a position.

I use the key:

student = {"name": "Feddy", "age": 20, "course": "Data Science"}

print(student["name"])

The result is:

Feddy

I can also access the age:

print(student["age"])

The result is:

20

This was the point where dictionaries started making sense to me.

Instead of thinking, "Which position is the age in?", I just ask for "age".

Using get()

There is another way to access a value:

student.get("name")

This also gives:

Feddy

The difference becomes useful when the key doesn't exist.

For example:

print(student.get("phone"))

Instead of raising an error, Python returns:

None

I can even provide a default value:

print(student.get("phone", "No phone number"))

Now I get:

No phone number

I found this useful when working with data where some information might be missing.

Adding new values

Dictionaries are changeable.

I can add a new key-value pair like this:

student["city"] = "Nairobi"

Now the dictionary contains the city as well.

I don't have to recreate the entire dictionary just to add one more piece of information.

Updating values

I can also change an existing value.

For example:

student["age"] = 21

Now the age is 21.

The same syntax is used for both adding and updating.

If the key already exists, the value changes.

If it doesn't exist, Python adds it.

Removing values

There are a few ways to remove dictionary items.

Using pop():

student.pop("city")

This removes the "city" entry.

I can also use del:

del student["age"]

And if I want to remove everything:

student.clear()

The dictionary itself still exists, but there is nothing inside it.

Checking if a key exists

I can check whether a key is in a dictionary using in.

For example:

"name" in student

This returns:

True

I can also use it in a condition:

if "phone" in student:

print("Phone number exists")

This became useful when dealing with information that isn't always available.

Finding the number of items

Just like with lists and tuples, I can use len().

student = {"name": "Feddy", "age": 20, "course": "Data Science"}

print(len(student))

The result is:

3

There are three key-value pairs in the dictionary.

Getting all keys

I can get all the keys using keys():

student.keys()

For example:

for key in student.keys():

print(key)

This would give me:

name

age

course

I use this when I only care about the labels.

Getting all values

I can get the values using values():

for value in student.values():

print(value)

This gives:

Feddy

20

Data Science

Getting keys and values together

This is one of the dictionary methods I use most.

items() gives me both:

for key, value in student.items():

print(f"{key}: {value}")

The output would be:

name: Feddy

age: 20

course: Data Science

This is especially useful when I want to go through all the information in a dictionary.

Looping through dictionaries

I can loop through a dictionary in different ways.

Just the keys:

for key in student:

print(key)

Just the values:

for value in student.values():

print(value)

Or both:

for key, value in student.items():

print(key, value)

I found .items() easiest when I wanted to actually work with the information.

Dictionary with numbers

Dictionaries don't have to store text.

For example:

prices = {"Bread": 80, "Milk": 120, "Sugar": 180}

I can get the price of milk:

print(prices["Milk"])

The result is:

120

I can also update it:

prices["Milk"] = 130

Now the price is 130.

This made dictionaries feel useful for things like products and prices.

A practical inventory example

Let's say I'm building a small shop inventory.

I could have:

product = {"name": "Bread", "price": 80, "quantity": 20}

Now I can access each piece of information:

print(product["name"])

print(product["price"])

print(product["quantity"])

I can also calculate the value of the stock:

stock_value = product["price"] * product["quantity"]

print(stock_value)

The result is:

1600

Now the dictionary is storing information, while my code is using that information to do something useful.

Nested dictionaries

This is where dictionaries become much more powerful.

A dictionary can contain another dictionary.

For example:

students = {

"student1": {"name": "Feddy", "age": 20, "course": "Data Science"},

"student2": {"name": "Amina", "age": 21, "course": "Python"}

}

Now I can access Feddy's name using:

print(students["student1"]["name"])

The result is:

Feddy

And Amina's course:

print(students["student2"]["course"])

The result is:

Python

At first this looked confusing because there are multiple brackets, but I realised I was simply going one dictionary level at a time.

A list of dictionaries

I can also combine dictionaries with lists.

For example:

students = [

{"name": "Feddy", "age": 20},

{"name": "Amina", "age": 21},

{"name": "Brian", "age": 19}

]

Now I have a list containing three dictionaries.

I can loop through them:

for student in students:

print(student["name"])

This gives:

Feddy

Amina

Brian

This structure started making a lot of sense to me because it looks much more like real data.

Dictionary comprehension

Just like lists have comprehensions, dictionaries do too.

For example:

squares = {number: number ** 2 for number in range(1, 6)}

The result is:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

I found this easier to understand after becoming comfortable with normal loops.

The same idea is happening, but Python lets me write it in a shorter form.

Copying dictionaries

Just like lists, I need to be careful when copying dictionaries.

If I do:

student2 = student

both variables refer to the same dictionary.

So changing one can affect the other.

To create a separate copy, I can use:

student2 = student.copy()

Now I can modify student2 without changing the original dictionary.

What I understood about dictionaries

The biggest thing I learnt is that dictionaries are really useful when the information needs labels.

With a list, I might have:

student = ["Feddy", 20, "Data Science"]

But now I have to remember that index 0 is the name, index 1 is the age, and index 2 is the course.

With a dictionary:

student = {"name": "Feddy", "age": 20, "course": "Data Science"}

I don't have to remember positions.

I just use the key I need.

Lists vs dictionaries

This is how I now think about the difference.

A list:

products = ["Bread", "Milk", "Sugar"]

is useful when I mainly care about the collection of items.

A dictionary:

product = {"name": "Bread", "price": 80, "quantity": 20}

is useful when I care about different pieces of information about one thing.

And I can combine them:

inventory = [

{"name": "Bread", "price": 80, "quantity": 20},

{"name": "Milk", "price": 120, "quantity": 15},

{"name": "Sugar", "price": 180, "quantity": 10}

]

That combination is something I expect to use a lot as I build bigger Python programs.

Final thoughts

Dictionaries took some getting used to because they are different from the position-based approach I was used to with lists.

But once I understood the idea of keys and values, everything started falling into place.

I can add information, update it, remove it, search for it, loop through it, and even put dictionaries inside other data structures.

The biggest thing I took away is simple:

A list helps me organise items.

A dictionary helps me organise information about those items.

That distinction has made choosing between the two much easier for me.

šŸ“° Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.