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.
Python code
21 linesdef 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
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
- Use `data.keys()`, `data.values()`, or `data.items()` directly for more granular inspection.
- 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
More from Dictionaries & sets
- Build a Case-Insensitive Dict with a Wrapper Class in Python medium
- Build a defaultdict histogram of categories in Python easy
- Build adjacency dict graph from edges in Python easy
- Build an OrderedDict insertion order demo in Python 3 easy
- Check Invertible Mapping for Duplicate Values in Python easy
- Compare Two Dictionaries in Python easy
Keep learning
Related tutorials and quizzes for this topic.