I'm trying to loop through a dictionary to get the size of each element associated with each of the keys. These dictionary elements are either arrays or a string. If its a string i need the number of characters in the string. If its an array, I need the size of the array.
import numpy as np
myDict = {'string': 'this is a string', 'arraySingle': np.array(12),
'array1': np.array([12]), 'multiarray': np.array((12, 12))}
for key in myDict.keys():
size = np.size(myDict[key])
try:
length = len(myDict[key])
except TypeError:
length = None
print('key "{}" has a length of {} and a size of {} '.format(key, length, size))
produces
key string has a length of 16 and a size of 1
key arraySingle has a length of None and a size of 1
key array1 has a length of 1 and a size of 1
key multiarray has a length of 2 and a size of 2
What i would really like is an answer of:
key "string" has a ___ of 16
key "arraySingle" has ___ of 1
key "array1" has a ___ of 1
key "multiarray" has a ___ of 2
how do I get that answer elegantly ? I would like to do it in one line as opposed to use something like
if isisntance(myDict[key], str):
print("do something")
elif isinstance(myDict[key], np.ndarray):
print("do something else")
lendoesn't work onnp.array? That seems odd, except for that fact that numpy allows multiple dimensions.lenon an array returns the first dimension. For a 1d array that would be the same assize. There's nothing wrong with having severalinstancetests or try/except. That's commonly done in Python andnumpycode. Package those tests in an function is you want to keep your code "clean".len. It's not iterable.np.array(1)vsnp.array([1])