+ 1

sum({1:2, 3:4}) -What is this code doing?

I saw this in a question and I have no idea what the sum function is doing here. Why the curly brackets? Is this a set of some kind? Why the colon? Is Python summing a range of some kind? No idea where to start and would appreciate any tips - thanks!

24th Jan 2019, 7:05 AM
adam
6 Answers
+ 6
The {1:2,3:4} apparently is a dictionary, not a set, here 1 and 3 are keys, while 2 and 4 are values. The sum() appears to be doing its work by summing the keys as I observed when running the code, it outputs 4 (sum of 1 + 3). Hth, cmiiw
24th Jan 2019, 7:14 AM
Ipang
+ 3
adam good test 👍, and you are right, only one will remain when duplicated. Can I suggest you to go one step further by guessing which value is stored, 2 or 3? and then please print the dict with duplicated key to see if your guess is correct. It's a fun way of self learning
25th Jan 2019, 12:39 AM
Gordon
Gordon - avatar
24th Jan 2019, 8:07 AM
Gordon
Gordon - avatar
+ 2
thanks Ipang and Gordon I thought it might be a dict summing the keys and played around with different inputs. one interesting thing is that if the same key repeats itself, it will only be counted once. eg, the output of this code is 1, not 2: print(sum({1:2,1:3}))
24th Jan 2019, 11:55 PM
adam
+ 1
Great find! 👍 adam There are two branch from here: In maths, and also in JavaScript, this is called set. Set is used when we are handling some real-life situation ~ Can you think of some? P. S. Let's begin with this interesting branch first. After that, I am going to show to how to put Dictionary into a function as keyworded argument and how to use Dictionary as the switch-case statement of Python. I am writing these here so I can remember to do so later.
25th Jan 2019, 10:51 PM
Gordon
Gordon - avatar
0
Gordon That was a good question! It saves the last one when there are duplicates. eg this code will output 99: dict1 = {1:3, 1:2, 1:99} print(dict1[1])
25th Jan 2019, 10:48 PM
adam