+ 1
could someone explain how the addition works with dict datatype
I'd really appreciate if someone told how this program works, and what's the significance of dict datatype. I would even appreciate if someone could redirect me to some of the programs that explains the dict datatype more clearer. Thank you in advance guys https://code.sololearn.com/cS0qeiyA5TGH/?ref=app
5 Answers
+ 4
dict = {1:15,5:10,4:26}
sum= 0
for key in dict:
sum = sum + dict[key]
print(sum)
your code was suming the keys, I edited it so now it sums the values.
a dictionary is a collection datatype. it caintains pairs of keys and values.
a key should be unique and of not mutable (not changeable) datatype.
a value can be of any datatype.
+ 1
Is there anyway I could add both the keys and values in total guys ?
And what if there's a string in the values, how would adding all the values work then
I'm having a tough time wrapping my head around dictionaries but yall are amazing thanks a ton guys
+ 1
Torg a use of a dictionary datatype could be like an English dictionary; you can use a word as a key and the definition of the word as it's value. (The key is an index)
Adding two or more strings is concatenation.
If the strings are digits you could convert to float or int. but it will throw an error if the strings contain non-digits so you can use it inside "try and except " for example.
You can sum both the keys and values in your dict simply because they all are integers.
for key in dict:
sum += key + dict[key]
I suggest to start the sololearn courses: beginner then intermediate then data structures. They will make things clearer.
And you can Google usages of python dictionary, to see some real world usages because actually I don't have experience with it.
- 3
Salom