You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对值为列表的字典中的元素进行类型断言

How to Assert All Elements in Dictionary Values (Lists) Are Integers?

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 sublist in My_dict.values()
  • Then, iterate over each item in that sublist
  • Check if each item is an integer
  • all() ensures all these checks return True

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 16:04:04