如何对值为列表的字典中的元素进行类型断言
Let's break down what's wrong with your current code first, then fix it properly.
Your original assertion checks if each list in the dictionary values is an integer—which will always fail, because those values are list objects, not int! Here's why:
# Your original code (flawed) assert all(isinstance(values, int) for values in My_dict.values()),"The values of the dict are not integer"
When you iterate over My_dict.values(), you're getting each entire list (like [127479365, 127480532]), so isinstance(values, int) is checking if that list is an integer—obviously false.
Correct Solutions
You need to nest your iteration: first loop through each list in the dictionary values, then loop through each element inside those lists.
1. Concise Nested Generator Expression
This is the most compact way to do it, using a nested generator inside all():
My_dict = {'chr7': [127479365, 127480532], 'chr8': [127474697, 127475864], 'chr9': [127480532, 127481699]} # Check every element in every sublist assert all(isinstance(item, int) for sublist in My_dict.values() for item in sublist), "Not all elements in the dictionary are integers"
The generator works like this:
- First, iterate over each
sublistinMy_dict.values() - Then, iterate over each
itemin thatsublist - Check if each
itemis an integer all()ensures all these checks returnTrue
2. Verbose Loop with Specific Error Messages
If you want more detailed error feedback (to know exactly which element/key is invalid), use explicit loops:
My_dict = {'chr7': [127479365, 127480532], 'chr8': [127474697, 127475864], 'chr9': [127480532, 127481699]} for key, sublist in My_dict.items(): for index, item in enumerate(sublist): assert isinstance(item, int), f"Element at position {index} in key '{key}' ({item}) is not an integer"
Now if an element fails, you'll get a clear message like:AssertionError: Element at position 0 in key 'chr7' ('not_an_int') is not an integer
3. Optional: First Validate Values Are Lists
If you want to ensure all dictionary values are actually lists before checking elements, add a preliminary assertion:
# First make sure all values are lists assert all(isinstance(sublist, list) for sublist in My_dict.values()), "Some dictionary values are not lists" # Then check element types assert all(isinstance(item, int) for sublist in My_dict.values() for item in sublist), "Not all elements are integers"
内容的提问来源于stack exchange,提问作者Manolo Dominguez Becerra

