+ 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!
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
+ 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
+ 2
https://www.sololearn.com/learn/JUMP_LINK__&&__Python__&&__JUMP_LINK/2450/
Play with the Try It Yourself
+ 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.
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])