say i have an array of dictionaries:
thisdict={}
thisdict[0]={1: 'one', 2: "two"}
thisdict[1]={3: 'three', 4:'four'}
thisdict[2]={5: 'five', 6:'six'}
How can I find its dimesion? I'm looking for (3,2) -- 3 dictionaries, each with 2 entries.
len(thisdict)
yields 3.
np.shape(thisdict)
returns ()
and
np.size(thisdict)
returns 1.
If I convert the dictionary to a dataframe via
import pandas as pd
tmp = pd.DataFrame.from_dict(thisdict)
then,
np.size(tmp)
= 18
and
np.shape(tmp)
=(6,3)
since tmp =
which still does't give me what I'm looking for.
I guess I could do
len(thisdict)
followed by
len(thisdict[0])
to get the two dimensions I'm interested in, but I assume there is a better way. What is the "correct" way of getting these two dimensions?
There is nothing wrong with len(thisdict)
and len(thisdict[0])
, provided that the 0
-key will always exist and all sub-dictionaries have the same length. If not, you could use something along the lines of
def dict_dims(mydict):
d1 = len(mydict)
d2 = 0
for d in mydict:
d2 = max(d2, len(d))
return d1, d2