moon knight
moon knight

Reputation: 37

getting the Length of all lists in a dictionary

listdict = {
  'list_1' : ['1'],
  'list_2' : ['1','2'],
  'list_3' : ['2'],
  'list_4' : ['1', '2', '3', '4']
}
    
print(len(listdict))

This is my code for example. I want it to print:

8

I have tried length as u can see but it prints 4 of course the amount of lists but I want it to print the amount of items in the lists. Is there a way where I can do this with one statement instead of doing them all seperately? Thanks in advance.

I tried using len(dictionaryname) but that did not work

Upvotes: 0

Views: 225

Answers (2)

Sash Sinha
Sash Sinha

Reputation: 22473

Consider utilizing another inbuilt function sum (len is a built in function):

>>> listdict = {
...   'list_1' : ['1'],
...   'list_2' : ['1','2'],
...   'list_3' : ['2'],
...   'list_4' : ['1', '2', '3', '4']
... }
>>> sum(len(xs) for xs in listdict.values())
8

As an aside, since python employs duck typing using Hungarian naming for variables in Python is kinda sus ngl...

Upvotes: 1

Andrej Kesely
Andrej Kesely

Reputation: 195563

You have 4 lists as values in your dictionary, so you have to sum the lengths:

print(sum(map(len, listdict.values())))

Prints:

8

Upvotes: 1

Related Questions