python - 如何在 Python 中查找字典数组(或字典的字典)的形状或维度

标签 python arrays dictionary shapes dimensions

假设我有一个字典数组:

thisdict={}
thisdict[0]={1: 'one', 2: "two"}
thisdict[1]={3: 'three', 4:'four'}
thisdict[2]={5: 'five', 6:'six'}

如何找到它的尺寸?我正在寻找 (3,2) -- 3 个字典,每个字典有 2 个条目。

len(thisdict) 产生 3。

np.shape(thisdict) 返回 ()

np.size(thisdict) 返回 1。

如果我通过将字典转换为数据框

import pandas as pd
tmp = pd.DataFrame.from_dict(thisdict)

那么,

np.size(tmp) = 18

np.shape(tmp) =(6,3)

自从 tmp=

enter image description here

这仍然没有给我我想要的东西。

我想我可以做到

len(thisdict) 后跟

len(thisdict[0])

获得我感兴趣的两个维度,但我认为有更好的方法。获取这两个维度的“正确”方法是什么?

最佳答案

len(thisdict)len(thisdict[0]) 没有任何问题,前提是 0 -key 始终存在并且所有子词典具有相同的长度。如果没有,您可以使用类似的东西

def dict_dims(mydict):
    d1 = len(mydict)
    d2 = 0
    for d in mydict:
        d2 = max(d2, len(d))
    return d1, d2

关于python - 如何在 Python 中查找字典数组(或字典的字典)的形状或维度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66033977/

相关文章:

JavaScript 数组没有正确索引?

python - Pandas:在条件后创建指示列

javascript - 类型错误 : i is undefined javascript leaflet api

python - 从字典中提取重复值

arrays - Marshal 一个 JSON Marshal 兼容映射到 XML

c++ - 下标值不是数组、指针或 vector ,C++

javascript - 最好使用 Lodash 按查找表对值进行排序

python - 提取列表,同时测试提取条目的条件

python - 验证棉花糖中的可选字段

python - 列出 python 类中的 @property 装饰方法