Skip to content

How to Check Types of Keys and Values in Python Dictionary

Learn how to validate Python dictionary keys and values against expected types using isinstance(), all(), and type hints for data validation.

Ensuring that a dictionary contains specific data types is a common requirement for data validation, especially when processing JSON input, configuration files, or API responses. Python's dynamic typing allows dictionaries to hold mixed types, but sometimes we need strict uniformity (e.g., a dictionary mapping strings to integers).

This guide explains how to validate that all keys and/or values in a dictionary conform to expected types.

Method 1: Using Iteration and isinstance() (Manual)

This method iterates through the dictionary and checks each item individually. It is useful if you want to print an error message specifying exactly which key or value failed validation.

def validate_dict_types(data, key_type, value_type):
    for key, value in data.items():
        if not isinstance(key, key_type):
            print(f"Invalid key type: {key} (Expected {key_type.__name__})")
            return False
        if not isinstance(value, value_type):
            print(f"Invalid value type for key '{key}': {value} (Expected {value_type.__name__})")
            return False
    return True

valid_data = {"age": 25, "score": 90}
invalid_data = {"age": 25, "score": "ninety"}

print(f"Valid Data check: {validate_dict_types(valid_data, str, int)}")
print(f"Invalid Data check: {validate_dict_types(invalid_data, str, int)}")

Output:

Valid Data check: True
Invalid value type for key 'score': ninety (Expected int)
Invalid Data check: False

Method 2: Using all() (Pythonic)

The most concise and readable way to validate types is using the all() built-in function with generator expressions. This returns True only if every element satisfies the condition.

Checking Keys

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

keys_are_valid = all(isinstance(k, str) for k in data)
print(f"Are all keys strings? {keys_are_valid}")

Output:

Are all keys strings? True

Checking Values

values_are_valid = all(isinstance(v, int) for v in data.values())
print(f"Are all values integers? {values_are_valid}")

Output:

Are all values integers? True

Checking Both (One-Liner)

is_valid_mapping = all(isinstance(k, str) and isinstance(v, int) for k, v in data.items())
print(f"Is strict str->int mapping? {is_valid_mapping}")

Output:

Is strict str->int mapping? True

Method 3: Using Type Hints (Static Analysis)

While runtime checks (like isinstance) are necessary for dynamic data, you should use Type Hints (typing) for development-time validation. Tools like mypy can catch these errors before you even run the code.

from typing import Dict

scores: Dict[str, int] = {
    "Alice": 95,
    "Bob": 88
}

Conclusion

To verify dictionary types in Python:

  1. Use all() for clean, boolean checks: all(isinstance(k, str) for k in d).
  2. Use loops if you need detailed error reporting on which item failed.
  3. Use Type Hints (Dict[KeyType, ValueType]) to prevent type errors during development.
Navigation