Codectionary / Developer documentation / Python

Nested Data Structures

Python's collections can contain other collections, letting you model real-world structured data like JSON responses, database records, or configuration files. A list of dictionaries is common for representing multiple similar records, while a dictionary of lists groups related items under keys. Accessing nested values just means chaining index/key lookups together.

Syntax

data = {"key": [{"nested_key": "value"}]}

Examples

List of Dictionaries

A very common pattern for representing multiple records, like rows from a database.

students = [
    {"name": "Fola", "grade": 85},
    {"name": "Zain", "grade": 92},
    {"name": "Jamal", "grade": 78}
]

for student in students:
    print(f"{student['name']}: {student['grade']}")

top_student = max(students, key=lambda s: s["grade"])
print(f"Top student: {top_student['name']}")

Dictionary of Lists

Grouping related items together under descriptive keys.

courses = {
    "frontend": ["HTML", "CSS", "JavaScript"],
    "backend": ["PHP", "Python", "MySQL"]
}

for category, techs in courses.items():
    print(f"{category}: {', '.join(techs)}")

courses["backend"].append("Node.js")
print(courses["backend"])

Accessing Deeply Nested Values

Chaining lookups to reach a value several levels deep.

data = {
    "user": {
        "name": "Fola",
        "address": {
            "city": "Manchester",
            "postcode": "M1 1AA"
        }
    }
}

print(data["user"]["address"]["city"])  # Manchester

# Safer access with .get() to avoid KeyErrors on missing keys
postcode = data.get("user", {}).get("address", {}).get("postcode")
print(postcode)

Iterating Nested Structures

Looping through a nested structure to process every value.

inventory = {
    "fruits": ["apple", "banana"],
    "vegetables": ["carrot", "potato"]
}

for category, items in inventory.items():
    print(f"{category.title()}:")
    for item in items:
        print(f"  - {item}")

Best practices

  • Use a list of dictionaries for collections of similar records, and a dictionary of lists for grouping items by category
  • Chain .get() calls with default empty dictionaries/lists when accessing deeply nested data that might be incomplete
  • Consider a dataclass or a small class instead of deeply nested dicts/lists once the structure gets complex, for better readability and type safety
  • Use the json module to convert nested Python structures to and from JSON when working with APIs or config files

At a glance

Purpose
Scripting and general-purpose applications
File extension
.py
Runs in
Python interpreter
Usually used with
Python standard library and packages

Specifications & further reading

Related Python documentation

Lists
A list is Python's built-in ordered, mutable collection type, created with square brackets. Lists can hold items of any type - even a mix of types - and support indexing, slicing, and a wide range of built-in methods for adding, removing, and reordering elements. Because they are mutable, lists can be changed in place after creation, which makes them the go-to structure for collections that grow or shrink over time.
Tuples
A tuple is an ordered, immutable collection, created with parentheses (or often just commas). Once created, a tuple's contents cannot be changed, added to, or removed - this immutability makes tuples faster than lists and safe to use as dictionary keys or in sets. Tuples are commonly used for fixed collections of related values, like coordinates or RGB colors, and for returning multiple values from a function.
Dictionaries
A dictionary stores data as key-value pairs, created with curly braces. Keys must be unique and hashable (strings, numbers, or tuples are common choices), while values can be anything, including other dictionaries or lists. Since Python 3.7, dictionaries maintain insertion order. They are one of the most heavily used data structures in Python, ideal for representing structured records, lookups, and mappings.
Sets
A set is an unordered collection of unique, hashable items, created with curly braces or the set() function. Sets automatically eliminate duplicates and support fast membership testing, along with mathematical set operations like union, intersection, and difference. They're especially useful for deduplicating data and for comparing two collections to find overlaps or differences.