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.

Easy Python 3.9+ Aug 9, 2026 Dictionaries & sets 13 views 0 copies

Python code

21 lines
Python 3.9+
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 {len(data)} elements")
        for item in sorted(data):
            print(f"  {item} ({type(item).__name__})")
    else:
        print(f"Unsupported type: {type(data).__name__}")


if __name__ == "__main__":
    sample_dict = {"name": "Alice", "age": 30, "active": True}
    sample_set = {3, 1, 2, 2, 4}
    
    check_data(sample_dict)
    print()
    check_data(sample_set)

Output

stdout
Dictionary with 3 keys
  name: Alice (str)
  age: 30 (int)
  active: True (bool)

Set with 4 elements
  1 (int)
  2 (int)
  3 (int)
  4 (int)

How it works

The helper uses isinstance to check whether the input is a dictionary or a set. For dictionaries, it prints the number of keys and then iterates over items() to show each key, its value, and the value's type. For sets, it prints the element count and then iterates over sorted(data) to display elements in a consistent order (sets are unordered). The type(value).__name__ gives a clean type name like 'str' or 'int'. The if __name__ == "__main__" guard ensures the demo runs only when the script is executed directly.

Common mistakes

  • Forgetting that sets are unordered, so iteration order may vary unless you sort them.
  • Using `type(data) == dict` instead of `isinstance(data, dict)`, which fails for subclasses.
  • Assuming duplicate values in a set are preserved; sets automatically remove duplicates.
  • Checking for a set before a dictionary, but a set can't be a dictionary, so order is fine.

Variations

  1. Use `data.keys()`, `data.values()`, or `data.items()` directly for more granular inspection.
  2. Use `pprint` from the standard library to pretty-print nested dictionaries or sets.

Real-world use cases

  • Debugging API responses by quickly printing the structure and types of a returned JSON dict.
  • Inspecting configuration dictionaries loaded from environment or file before applying settings.
  • Verifying the contents of a set of unique user IDs before batch processing.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.