getting the Length of all lists in a dictionary

Question:

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

Asked By: moon knight

||

Answers:

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

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

Prints:

8
Answered By: Andrej Kesely

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

Answered By: Sash Sinha
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.