Python: practical uses for summing up dictionary keys? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Python: practical uses for summing up dictionary keys?

Today I've learned that print(sum({key1:value1, key2:value2, keyn:valuen, })) outputs the sum of all the keys. For example: print(sum({1:2,3:4,5:6, 100:200})) outputs 109 What kind of practical use could this have?

18th Sep 2020, 7:28 PM
Solus
Solus - avatar
3 Answers
+ 7
Mirielle[ InAcTiVe ] , he has asked about to sum the keys and not the values. But i go with you, that in most cases the values are processed and not the keys. May be its just an exercise?
18th Sep 2020, 7:42 PM
Lothar
Lothar - avatar
+ 3
From Mirielle[ InAcTiVe ] example, May be here, to know the number of working days, keys works as will be equal to number of keys.. And if you take it as "num_of_sales in a day" : "amount" then sum of keys is sum of sales.. Sum of values is sum of amount..
18th Sep 2020, 7:58 PM
Jayakrishna 🇮🇳
+ 2
when you loop through a dictionary without passing a dictionary function (ie. dict.items()), it returns the keys. That is probably why it’s adding up the keys
19th Sep 2020, 1:38 AM
Jacob
Jacob - avatar