Python Dictionaries: Complete Beginner Guide

Published on: July 10, 2026
Reading time: 4 minutes
Dicionário com o logo do Python em uma página e o texto 'Dicionário Python'

Python dictionaries store information as key-value pairs. They are one of the most useful data structures in the language because they let you give meaningful names to values instead of relying only on numeric positions.

Imagine a contact record. A list could store ["Maya", 29, "[email protected]"], but you must remember what every position means. A dictionary makes the same data self-explanatory:

person = {
    "name": "Maya",
    "age": 29,
    "email": "[email protected]"
}

This guide covers creation, access, updates, deletion, loops, nested dictionaries, comprehensions, merging, common mistakes, and practical projects. Readers who are still comparing collection types can also review lists, tuples, sets, and dictionaries.

What is a Python dictionary?

A dictionary is a mutable mapping. Each key identifies one value. Keys must be unique and hashable, while values can be almost any Python object: numbers, strings, lists, functions, or other dictionaries.

Dictionaries preserve insertion order in modern Python, but their main purpose is lookup by key. A list answers “what is at position 2?” A dictionary answers “what is the email?”

product = {
    "name": "Mechanical keyboard",
    "price": 89.90,
    "in_stock": True
}

print(product["name"])

The official Python tutorial on dictionaries describes the same mapping model and its core operations.

Creating dictionaries

The most common syntax uses braces. Separate each key from its value with a colon and separate pairs with commas.

empty = {}

student = {
    "name": "Noah",
    "grades": [8.5, 9.0, 7.8],
    "active": True
}

You can also use dict():

settings = dict(theme="dark", language="en", notifications=True)

Strings and numbers are common keys. Tuples can also be keys when all their elements are immutable. Lists cannot be dictionary keys because they can change. The dedicated guide to Python tuples explains why immutability matters.

Accessing values safely

Square brackets return the value for a key:

user = {"name": "Ava", "role": "editor"}
print(user["role"])

If the key does not exist, Python raises KeyError. The get() method is safer when a value may be missing:

print(user.get("email"))           # None
print(user.get("email", "Unknown"))

Use brackets when a key is required and a missing key means the program has invalid data. Use get() when absence is expected. For broader error-handling patterns, see the guide to try and except in Python.

Adding and changing items

Dictionaries are mutable, so assignment can create a new item or replace an existing value.

profile = {"name": "Leo", "city": "Toronto"}
profile["age"] = 34
profile["city"] = "Vancouver"

Use update() to apply several changes:

profile.update({
    "job": "Developer",
    "remote": True
})

Python 3.9 and newer also support the merge operator:

defaults = {"theme": "light", "page_size": 20}
custom = {"theme": "dark"}
final = defaults | custom

When the same key exists in both dictionaries, the value on the right wins.

Removing dictionary items

Use del when the key must exist:

cart = {"book": 2, "pen": 5, "notebook": 1}
del cart["pen"]

pop() removes a key and returns its value. A default prevents an error when the key is absent.

quantity = cart.pop("book", 0)
print(quantity)

popitem() removes the last inserted pair, while clear() removes everything.

Important dictionary methods

The three most common view methods are:

  • keys(): all keys
  • values(): all values
  • items(): key-value pairs
prices = {"coffee": 3.50, "tea": 2.80, "juice": 4.10}

print(list(prices.keys()))
print(list(prices.values()))
print(list(prices.items()))

These objects are dynamic views. If the dictionary changes, the view reflects the change.

Looping through dictionaries

A regular for loop iterates over keys:

inventory = {"laptop": 8, "mouse": 24, "monitor": 11}

for item in inventory:
    print(item)

Use items() when you need both parts:

for item, quantity in inventory.items():
    print(f"{item}: {quantity}")

This pattern combines dictionaries with the skills covered in the Python for-loop guide.

Checking whether a key exists

The in operator checks keys, not values:

account = {"username": "sam", "verified": False}

if "verified" in account:
    print("Verification field exists")

To search values, use in account.values(). The full guide to the Python in operator covers membership tests in other collections.

Nested dictionaries

A dictionary can contain another dictionary. This is common in JSON, API responses, configuration files, and application state.

company = {
    "engineering": {
        "manager": "Priya",
        "employees": 18
    },
    "design": {
        "manager": "Chris",
        "employees": 7
    }
}

print(company["engineering"]["manager"])

Deep nesting can become hard to read. Break complex data into smaller variables or classes when the structure grows.

Dictionary comprehensions

A dictionary comprehension creates a mapping from an iterable:

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

You can add a condition:

even_squares = {
    number: number ** 2
    for number in range(1, 11)
    if number % 2 == 0
}

Comprehensions are useful when the transformation is short and clear. A normal loop is better when several steps or validations are required.

Practical example: product catalog

products = {
    "KB100": {"name": "Keyboard", "price": 59.90, "stock": 12},
    "MS200": {"name": "Mouse", "price": 24.90, "stock": 30},
}

def add_product(code, name, price, stock):
    if code in products:
        raise ValueError("Product code already exists")

    products[code] = {
        "name": name,
        "price": price,
        "stock": stock,
    }

def inventory_value():
    return sum(
        item["price"] * item["stock"]
        for item in products.values()
    )

add_product("HD300", "External drive", 79.90, 6)
print(f"Inventory value: ${inventory_value():.2f}")

This example combines mappings, validation, loops, functions, and numeric formatting. The guide to Python functions provides more detail on reusable program structure.

Common mistakes

Using a missing key directly

Prefer get(), a membership test, or explicit exception handling when the key is optional.

Trying to use a list as a key

Keys must be hashable. Convert stable coordinate-like data to a tuple.

Changing a dictionary while iterating

Removing keys inside a loop over the same dictionary can raise an error. Iterate over list(dictionary) when deletion is necessary.

Creating an accidental shallow copy

copy() duplicates the outer dictionary, but nested mutable objects are still shared. Use copy.deepcopy() when independent nested data is required.

When should you use a dictionary?

Choose a dictionary when data has meaningful labels, fast lookup matters, or one value must map to another. Typical examples include user profiles, application settings, caches, counters, product catalogs, API data, and indexes.

Choose a list when position and sequential order are the main concerns. Choose a set when uniqueness and fast membership tests matter. Choose a tuple for a fixed, immutable record.

Conclusion

Python dictionaries provide readable key-based access, fast lookup, flexible values, and a rich set of methods. Start with creation and safe access, then practice loops, nested structures, comprehensions, and merging. Once these patterns become familiar, dictionaries will appear naturally in nearly every useful Python project.

For additional reference, consult the official dictionary type documentation and practice by building a small address book, inventory, or configuration manager.

Share:

Facebook
WhatsApp
Twitter
LinkedIn

Article content

    Related articles

    Programador pensando enquanto analisa código em dois monitores
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Learn Programming from Scratch: Beginner Guide

    Learn programming from scratch with a practical roadmap covering logic, languages, tools, exercises, projects, debugging, Git, and consistent study habits.

    Ler mais

    Tempo de leitura: 6 minutos
    10/07/2026
    ícone de loop com o texto 'For' abaixo
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python for Loops: Complete Beginner Guide

    Learn Python for loops with sequences, range, enumerate, zip, dictionaries, nested loops, break, continue, comprehensions, and practical examples.

    Ler mais

    Tempo de leitura: 4 minutos
    10/07/2026
    Manipulação e formatação de strings em Python
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python Strings: Complete Beginner Guide

    Learn Python strings with creation, indexing, slicing, methods, formatting, Unicode, searching, validation, splitting, joining, and practical examples.

    Ler mais

    Tempo de leitura: 4 minutos
    10/07/2026
    código Python de uma tupla com o texto separado formando a frase "O que são tuplas?"
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python Tuples: Complete Beginner Guide

    Learn Python tuples with creation, packing, unpacking, indexing, immutability, methods, named records, function returns, and practical examples.

    Ler mais

    Tempo de leitura: 5 minutos
    10/07/2026
    símbolo de PI
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python Floats: Complete Beginner Guide

    Learn Python floats with decimal values, arithmetic, conversion, rounding, precision limits, comparisons, Decimal, math functions, and practical examples.

    Ler mais

    Tempo de leitura: 4 minutos
    10/07/2026
    notebook mostrando tela a teclado
    Fundamentals
    Foto de perfil de Leandro Hirt da Academify

    Python Input and Output: Complete Guide

    Learn Python input and output with input(), print(), conversions, validation, formatting, files, command-line arguments, and practical interactive programs.

    Ler mais

    Tempo de leitura: 4 minutos
    10/07/2026