Home > Back-end >  getting the Length of all lists in a dictionary
getting the Length of all lists in a dictionary

Time:11-13

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

CodePudding user response:

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

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

Prints:

8

CodePudding user response:

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...

  • Related