Ensuring data consistency is critical in Python programming. When processing a dictionary, you often need to verify that all values share a common data type (e.g., all integers for scores, or all strings for names) to avoid runtime TypeError exceptions during operations.
This guide explains how to use the all() function, isinstance(), and iterator logic to efficiently check for type uniformity in dictionaries.
Method 1: Using all() and isinstance() (Recommended)
If you know the expected type beforehand (e.g., you expect all values to be integers), using all() with a generator expression is the most readable and Pythonic approach.
data = {"score1": 10, "score2": 20, "score3": 30}
are_all_ints = all(isinstance(val, int) for val in data.values())
print(f"All integers? {are_all_ints}")
mixed_data = {"name": "Alice", "age": 30}
are_all_strs = all(isinstance(val, str) for val in mixed_data.values())
print(f"All strings? {are_all_strs}")Output:
All integers? True
All strings? FalseMethod 2: Comparing Against the First Element
If you don't know the type in advance but simply want to ensure consistency (i.e., they are all the same, regardless of what that type is), you can grab the type of the first value and compare the rest against it.
data = {"a": 1.5, "b": 2.5, "c": 3.0}
values_iter = iter(data.values())
try:
first_type = type(next(values_iter))
is_uniform = all(isinstance(val, first_type) for val in values_iter)
print(f"Is uniform? {is_uniform} (Type: {first_type})")
except StopIteration:
print("Dictionary is empty.")Output:
Is uniform? True (Type: <class 'float'>)Method 3: Checking Against Multiple Allowed Types
Sometimes "same type" is broader, like allowing both int and float (numeric). isinstance() accepts a tuple of types.
measurements = {"temp": 23.5, "humidity": 60, "pressure": 1013.2}
is_numeric = all(isinstance(val, (int, float)) for val in measurements.values())
print(f"Is numeric? {is_numeric}")Output:
Is numeric? TrueHandling Empty Dictionaries
An empty dictionary technically satisfies the condition "all values are of type X" (vacuously true). However, logic relying on the first element (Method 2) will crash if not handled.
empty_data = {}
print(all(isinstance(x, int) for x in empty_data.values()))
if not empty_data:
print("Empty dictionary (Uniform by definition).")
else:
passOutput:
True
Empty dictionary (Uniform by definition).Conclusion
To check if dictionary values share the same type:
- Use
all(isinstance(v, Type) for v in d.values())if you know the specific type you require. - Use
iter()andnext()to infer the type dynamically from the first element if the specific type doesn't matter, just uniformity. - Handle empty dictionaries gracefully, as they contain no types to check.