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": "John", "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": "John",
        "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

Runtime & versions

Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Python language reference

Specifications & further reading