Reference library

Dictionaries & sets

Key–value maps, uniqueness, counting, grouping, and fast lookups.

4 matches
Dictionaries & sets easy

How to Check Data Type and Inspect Dictionaries and Sets in Python

Inspect dictionaries and sets by printing their contents, types, and sizes using a small helper function.

dictionaries sets isinstance
Python
def check_data(data):
    """Helper to inspect dictionaries and sets."""
    if isinstance(data, dict):
        print(f"Dictionary with {len(data)} keys")
        for key, value in data.items():
            print(f"  {key}: {value} ({type(value).__name__})")
    elif isinstance(data, set):
        print(f"Set with {le…
13 0 Open
Dictionaries & sets easy

How to Use MappingProxyType to Create Immutable Dict Views in Python

Create a read-only, immutable view of a dictionary using MappingProxyType from the types module, while the original dict stays mutable.

mappingproxytype dict immutable
Python
from types import MappingProxyType

config = {"debug": True, "port": 8080}

# Create an immutable read-only view of the dict
read_only_config = MappingProxyType(config)

print(f"Read-only value: {read_only_config['debug']}")
print(f"Dict is mapping: {isinstance(read_only_config, dict)}")

# Original dict can still be …
13 0 Open
Dictionaries & sets easy

How to Validate JSON Types per Key in Python

Load a JSON object and validate the type of each key against an expected schema, reporting missing or mismatched fields.

json validation types
Python
import json
from typing import Any, Dict, Type

def validate_json_types(data: Dict[str, Any], schema: Dict[str, Type]) -> Dict[str, str]:
    """Validate that each key in data matches the expected type in schema."""
    errors = {}
    for key, expected_type in schema.items():
        if key not in data:
            e…
15 0 Open
Dictionaries & sets easy

Parse Env Vars into Typed Dict in Python

Convert a list of environment variable names into a dictionary with automatically detected types (bool, int, float, or string), defaulting missing vars to None.

env-vars type-conversion dict
Python
import os
from typing import Any, Dict


def parse_env_vars(env_names: list[str], env: Dict[str, str] | None = None) -> Dict[str, Any]:
    """Parse a list of environment variable names into a typed dict.

    Each variable is parsed as:
    - bool: "true"/"false" (case-insensitive)
    - int: if it can be converted t…
13 0 Open

Browse by section

Each section groups closely related Python snippets.

Dictionaries & sets — Python code examples

What you will find here

This page collects dictionaries & sets snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.