Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 691
Tijmen Avatar asked Nov 26 '25 05:11

Tijmen


1 Answers

You can use the sum of a comprehension:

sum((len(v) for v in d.values()))
like image 156
Serge Ballesta Avatar answered Nov 27 '25 18:11

Serge Ballesta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!