On this page

Dictionaries

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

What a Dictionary Is​

A dictionary is Python’s built‑in mapping type. It stores data as key‑value pairs, allowing you to associate a unique key with a specific value. Dictionaries are unordered, mutable, and optimized for fast lookups.

A dictionary is written using curly braces:


person = {

    "name": "Alice",

    "age": 30,

    "city": "Osaka"

}

Keys must be unique and immutable (strings, numbers, tuples). Values can be any Python object.

Why Dictionaries Matter​

Dictionaries are essential for representing structured data. They allow you to:

They are one of the most widely used data structures in Python.

Creating Dictionaries​

You can create dictionaries in several ways:


empty = {}

data = {"a": 1, "b": 2}

converted = dict([("x", 10), ("y", 20)])

The dict() constructor accepts key‑value pairs in various formats.

Accessing Values​

Use a key inside square brackets to retrieve a value.


person = {"name": "Alice", "age": 30}



print(person["name"])   # Alice

If the key does not exist, Python raises a KeyError.

Safe Access with get()​

Use get() to avoid errors and provide a default value.


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

This is useful when working with incomplete or optional data.

Adding and Updating Entries​

Dictionaries are mutable, so you can add or modify key‑value pairs.


person["city"] = "Osaka"     # add

person["age"] = 31           # update

If the key exists, its value is replaced.

Removing Entries​

Python provides several ways to remove items:


person.pop("age")        # removes and returns the value

del person["name"]       # deletes the key entirely

person.clear()           # removes all items

Choose the method based on whether you need the removed value.

Checking Membership​

Use the in operator to check whether a key exists.


"user" in {"user": 1, "role": "admin"}   # True

Membership checks apply to keys, not values.

Looping Through Dictionaries​

Dictionaries support several iteration patterns.

Looping Over Keys​


for key in person:

    print(key)

Looping Over Values​


for value in person.values():

    print(value)

Looping Over Key‑Value Pairs​


for key, value in person.items():

    print(key, value)

This pattern is essential for processing structured data.

Dictionary Methods You Should Know​

These built‑in methods are fundamental:

These operations appear frequently in real‑world Python code.

Nested Dictionaries​

Dictionaries can contain other dictionaries, enabling hierarchical data structures.


user = {

    "name": "Alice",

    "address": {

        "city": "Osaka",

        "zip": "530‑0001"

    }

}

Access nested values using multiple keys:


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

Nested dictionaries are essential for working with JSON, APIs, and configuration files.

When to Use Dictionaries​

Use a dictionary when:

Dictionaries provide clarity and efficiency in data‑driven programs.

Summary​

Dictionaries are powerful, flexible, and central to Python programming. They allow you to store and manipulate structured data efficiently using key‑value pairs. Mastering dictionaries prepares you for working with APIs, data processing, configuration management, and more advanced data structures throughout the rest of this module.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Tuples

Next

Sets