Search code examples
pythonpython-3.xdictionarystring-length

How to get the total length of all dictionary values (strings)


Say I have a dictionary that contains a bunch of strings:

d = {'seq1':'AGG', 'seq2':'GCCG', 'seq3':'', 'seq4':'TTAAA'}

What is the best way to get the sum of all the lengths of the values? In this example, the total length is 3 + 4 + 0 + 5, so I want the output to be 12.

Is it possible to do this without using loops?


Solution

  • You can use the sum of a comprehension:

    sum((len(v) for v in d.values()))