Python

Dictionaries in Python: Everything You Need to Know – Lesson 10

Among Python’s most versatile data structures, dictionaries stand out. They help us represent structured data with keys and values, such as user information, system settings, and API responses. In this tenth lesson of our Python course, I will show you how dictionaries work, how to manipulate them, and why you should master them.

What is a dictionary in Python?

Dictionaries in Python are collections of key:value pairs. They are mutable, dynamic, and do not allow duplicate keys. The syntax is simple:

data = {"name": "Ana", "age": 30, "city": "São Paulo"}
print(data)
# Output: {'name': 'Ana', 'age': 30, 'city': 'São Paulo'}

You can also use other types as keys, as long as they are hashable, such as tuples:

coordinates = {(1, 2): "Point A", (3, 4): "Point B"}
print(coordinates)
# Output: {(1, 2): 'Point A', (3, 4): 'Point B'}

This is great when I need to index values by coordinates or complex pairs.

Accessing values and manipulating dictionaries in Python

To access a value, just use the key in square brackets:

print(data["name"])
# Output: Ana

If I try to access a key that does not exist, I get an error. To avoid this, I use the get() method:

print(data.get("email"))
# Output: None

This behavior is very useful when I am dealing with user input or data from external sources, where I can’t always be sure of the structure.

I can add or modify pairs easily:

data["email"] = "ana@email.com"
data["age"] = 31
print(data)
# Output: {'name': 'Ana', 'age': 31, 'city': 'São Paulo', 'email': 'ana@email.com'}

To remove a pair, pop() is very straightforward:

data.pop("city")
print(data)
# Output: {'name': 'Ana', 'age': 31, 'email': 'ana@email.com'}

If you want to clear the entire dictionary:

data.clear()
print(data)
# Output: {}

And to copy a dictionary without affecting the original:

data = {"name": "Ana", "age": 30}
copy = data.copy()
print(copy)
# Output: {'name': 'Ana', 'age': 30}

Iterating over dictionaries in Python

To loop through a dictionary, I usually use for with the items() method:

for key, value in data.items():
    print(f"{key}: {value}")
# Output:
# name: Ana
# age: 30

If I only want the keys or the values, I can use keys() or values():

for key in data.keys():
    print(key)
# Output:
# name
# age
for value in data.values():
    print(value)
# Output:
# Ana
# 30

I can also check whether a key exists:

if "email" in data:
    print("Key found!")
else:
    print("Key missing!")
# Output: Key missing!

Nested dictionaries: a powerful feature

You can create dictionaries inside dictionaries. This is very common when I deal with structured data from APIs, for example:

user = {
    "name": "Carlos",
    "email": "carlos@email.com",
    "address": {
        "city": "Belo Horizonte",
        "state": "MG"
    },
    "permissions": ["admin", "editor"]
}

print(user["address"]["city"])
# Output: Belo Horizonte

And I can navigate more complex structures that mix lists and dictionaries:

system = {
    "users": [
        {"name": "Ana", "active": True},
        {"name": "João", "active": False}
    ]
}

for u in system["users"]:
    if u["active"]:
        print(u["name"])
# Output:
# Ana

Best practices with dictionaries in Python

A few tips I usually follow:

  • I always check that the key exists before accessing it directly.
  • I use defaultdict from the collections module when I need default values.
  • I take advantage of dict comprehensions to build dictionaries elegantly.
  • When I need to preserve insertion order, I rely on the default behavior of Python 3.7+, which already guarantees it.

Dict comprehension example:

squares = {x: x**2 for x in range(5)}
print(squares)
# Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

And with defaultdict:

from collections import defaultdict

count = defaultdict(int)
words = ["python", "code", "python", "dictionary"]

for word in words:
    count[word] += 1

print(count)
# Output: defaultdict(<class 'int'>, {'python': 2, 'code': 1, 'dictionary': 1})

Real-world use cases for dictionaries in Python

Imagine you are building a shopping list. A dictionary can help you store the items and their quantities:

shopping = {
    "apple": 4,
    "banana": 6,
    "bread": 1
}

for item, quantity in shopping.items():
    print(f"{item}: {quantity}")
# Output:
# apple: 4
# banana: 6
# bread: 1

If I want to add an item or update its quantity:

shopping["banana"] = 10
shopping["milk"] = 2
print(shopping)
# Output: {'apple': 4, 'banana': 10, 'bread': 1, 'milk': 2}

This is a simple example, but it shows well how dictionaries in Python can be applied to everyday tasks in a practical way.

Conclusion

Mastering dictionaries in Python is essential for anyone who wants to write clean, expressive, and efficient code. They show up in practically every project I work on, whether on the backend or in automation scripts. Understanding how they work lets you handle JSON, configuration, and dynamic data storage much better. The more I use Python, the more I realize that dictionaries are the foundation of idiomatic, robust programming.

If you want to dig deeper, I recommend the official documentation on dictionaries.

Vinicius Sodré

Formado em Ciência da Computação pela Unicarioca, desenvolvedor de software com 15 anos de experiência em grandes empresas nacionais e multinacionais. Vinicius está à frente deste blog, feito de desenvolvedor para desenvolvedores de iniciantes a experientes.

Compartilhar
Publicado por:
Vinicius Sodré

Posts Recentes

Loops in Python: Run Code Repeatedly – Lesson 6

Loops in Python are one of the most fundamental concepts in any programming language. They…

2 years atrás

Conditional Statements in Python: Control the Flow – Lesson 5

When developing software, one of the most common tasks is controlling the program's flow of…

2 years atrás

Learn How to Manipulate Strings in Python – Lesson 4

Manipulating strings in Python is one of the most common tasks, and Python offers incredibly…

2 years atrás

Data Types in Python: Understanding Primitive Types – Lesson 3

Understanding data types in Python is one of the first steps to mastering the language.…

2 years atrás

Garbage Collector in .NET: Avoid Errors and Improve Performance

The Garbage Collector (GC) is one of the essential pillars of memory management in .NET.…

2 years atrás

How to Create Variables in Python – Python Course Lesson 2

Learning how to create variables in Python is one of the first steps toward mastering…

2 years atrás

Este blog utiliza cookies. Se você continuar assumiremos que você está satisfeito com ele.

Leia Mais...