![](/img/trans.png)
[英]How convert list of dictionaries to a dictionary of dictionaries in 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.