0

Can anyone explain how the below code works.

ages = {"Dave": 24, "Mary": 42, "John": 58} y=ages #print(ages["Dave"]) #print(ages["Mary"]) y["Mary"]=25 print(y) print(ages)

16th Mar 2017, 4:39 AM
Abin Singh R
Abin Singh R - avatar
3 Answers
+ 2
y=ages #y and ages point to the same dictionary y["Mary"]=25 #changes Mary's age from 42 to 25 print(y) #prints the contents of the dictionary print(ages) #prints the contents of *the same* dictionary
16th Mar 2017, 6:04 AM
Álvaro
+ 1
Simple types (like int) behave quite differently than complex types (like dicts or lists). When you assign a dict to another dict, you're actually managing *references* to objects. That is, in the first example, both y and ages "point" to the same dict. While managing ints, you're accessing the actual contents of the variables (no references nor pointers involved), so you're actually assigning different "copies" of the value. That's why, in the second example, a and b have two different values.
16th Mar 2017, 7:51 AM
Álvaro
0
okay fine I understood about dict are tagged to y and ages.. so we got same answer. but here is another example .. can you explain. a=1 b=a b=20 print(a) print(b)
16th Mar 2017, 7:44 AM
Abin Singh R
Abin Singh R - avatar