sue
sue

Reputation: 13

Find the length of list present inside the dict

sf is my dictionary that looks like:

    sf = {'DummyCustomer9': 
          array([list(['DummyCustomer9_subfolder1', 
                       'DummyCustomer9_subfolder2', 
                       'DummyCustomer9_subfolder3'])]
                ,dtype=object) 

I used the below piece of code to get the length, but it has returned me length of j is 1. Ideally it should count inside return me 3. How can I get the count of elements ?

     for i,j in sf.items():
        print(len(j)),j)

output

1 [list(['DummyCustomer9_subfolder1', 'DummyCustomer9_subfolder2', 'DummyCustomer9_subfolder3'])]

Upvotes: 0

Views: 70

Answers (1)

MrRBM97
MrRBM97

Reputation: 169

I have simplified your code as you do not need to have list() within the array() you can simply have a list set out with [], so rather than:

sf = {'DummyCustomer9': 
          array([list(['DummyCustomer9_subfolder1', 
                       'DummyCustomer9_subfolder2', 
                       'DummyCustomer9_subfolder3'])]
                ,dtype=object) 

you would have:

sf = {
    'DummyCustomer9': np.array(
        ['DummyCustomer9_subfolder1', 
         'DummyCustomer9_subfolder2', 
         'DummyCustomer9_subfolder3'], dtype='O')

Therefore it is a lot easier to get the length of the list within the np.array, by doing:

for k, v in sf.items():
    print(len(v), v)

For brevity the full code would be:

import numpy as np

sf = {
    'DummyCustomer9': np.array(
        ['DummyCustomer9_subfolder1',
         'DummyCustomer9_subfolder2',
         'DummyCustomer9_subfolder3'], dtype='O')
}

for k, v in sf.items():
    print(len(v), v)

Upvotes: 1

Related Questions