簡體   English   中英

如何在 Python 中查找字典數組(或字典的字典)的形狀或維度

[英]How to find the shape or dimension of an array of dictionaries (or dictionary of dictionaries) in Python

假設我有一系列字典:

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。

如果我通過將字典轉換為 dataframe

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

然后,

np.size(tmp) = 18

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

因為 tmp =

在此處輸入圖像描述

這仍然沒有給我我想要的東西。

我想我能做到

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM