Python中如何打印字典内嵌套numpy数组的形状?
Hey there! Let's break down why you're hitting that error and how to fix it quickly.
问题根源
When you call abc.values(), you're getting a dict_values object — this is just a view of all the values in your dictionary, not the actual numpy array itself. Since it's a dictionary-specific collection type, it doesn't have the shape attribute that numpy arrays do.
解决方案
Depending on whether your dictionary has one or multiple numpy array values, here are the right approaches:
1. 当字典只有一个键值对时(你的场景)
You can either convert the dict_values to a list and grab the first element, or use an iterator to fetch the first value more efficiently:
import numpy as np abc = {"a":np.array([[np.array([1,2,3])]])} # 方法1:转列表取第一个元素 array_val = list(abc.values())[0] print(array_val.shape) # 输出: (1, 1, 3) # 方法2:用迭代器获取(更高效,无需创建完整列表) array_val = next(iter(abc.values())) print(array_val.shape) # 同样输出: (1, 1, 3)
2. 当字典有多个numpy数组值时
Loop through all the values and print each shape individually:
abc_multi = { "a": np.array([1,2,3]), "b": np.array([[1,2],[3,4]]), "c": np.array([[[1,2],[3,4]],[[5,6],[7,8]]]) } for key, val in abc_multi.items(): print(f"数组{key}的形状: {val.shape}") # 输出: # 数组a的形状: (3,) # 数组b的形状: (2, 2) # 数组c的形状: (2, 2, 2)
额外说明
If you need to access the array by its key (which is often clearer than grabbing values blindly), you can just use the key directly:
print(abc["a"].shape) # 同样得到 (1, 1, 3)
This is actually the most readable approach if you know the key name upfront!
内容的提问来源于stack exchange,提问作者utsav bhavsar

