0

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")
5
  • I don't think you mean "key" here. Commented May 7, 2020 at 18:23
  • I wonder why len doesn't work on np.array? That seems odd, except for that fact that numpy allows multiple dimensions. Commented May 7, 2020 at 18:28
  • fair point Mark, i tried to clarify "key". to your second comment, i have noooo idea.... interesting problem though Commented May 7, 2020 at 18:33
  • 1
    len on an array returns the first dimension. For a 1d array that would be the same as size. There's nothing wrong with having several instance tests or try/except. That's commonly done in Python and numpy code. Package those tests in an function is you want to keep your code "clean". Commented May 7, 2020 at 22:22
  • 1
    However a 0d array, with 1 scalar value, will not have a len. It's not iterable. np.array(1) vs np.array([1]) Commented May 8, 2020 at 0:41

2 Answers 2

2

I am not sure what you are looking for, but I think this will help solve your question:

import numpy as np
myDict = {'string':  'this is a string', 'array': np.array((12))}
for key in myDict.keys():
    try:
        length = len(myDict[key])
        length_type = 'length' 
    except TypeError:
        length = np.size(myDict[key])
        length_type = 'size' 

    print('key "{}" has a {} of {}'.format(key, length_type, length))

output:

key "string" has a length of 16
key "array" has a size of 1
Sign up to request clarification or add additional context in comments.

2 Comments

this is disappointing, but the best answer so far, i'll award
@SBFRF I am not sure if you can do anything significantly different. They are different data types and hence require a checking statement somehow. Was the output not what you were looking for? maybe you can elaborate more on your desired output and we can try to help better. Also, thank you for the accept :)
0

When you have complicated logic that you want to clear out of the way, package it into its own function.

def size(x):
    if isinstance(x, np.array):
        return np.size(x)
    try:
        return len(x)
    except TypeError:
        return 1

print('key "{}" has a size of {}'.format(key, size(myDict[key])))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.