ymmx
ymmx

Reputation: 4967

How make a reference to a particular key/values dict?

I'm wondering if it is possible to make a reference to a particular key of a dict.

For instance, if I create a dict :

D={0:[1,2,3],1:['a','b','c']}

and a reference to the 0 list

ref_D_0=D[0]

I can print the value of the 0 key of D dict

print(ref_D_0)
# [1, 2, 3]

but if I modify the D dict:

D[0]=[3,2,1]
print(D) # {0: [3, 2, 1], 1: ['a', 'b', 'c']}

then ref_D_0 still give me the previous value of D[0]

print(ref_D_0) 
#[1, 2, 3]

What I would expect is that ref_D_0 refers to D[0] instead making a copy of it. Did I misunderstand something about referencing in python?

Upvotes: 0

Views: 88

Answers (3)

blue note
blue note

Reputation: 29081

When you write ref_D_0=D[0] the value ref_D_0 uses the dict to look up its current value (the list [1,2,3]). After that, it has no connection to the dict, just to the value of its 0 key. If you change that list *(eg D[0][1] = 5), the value of ref_D_0 will change too. However, you don't. Instead, you assign a new value. What you do is essentially equivalent to

a = [1,2,3]
b = a # they point to the same list
a = [3,2,1] # they don't anymore

So, to sum up, you didn't misundestand. ref_D_0 refers to the object currently in D[0], it is not a copy. However, if that object is replaced (not changed), your ref_D_0 still refers to the original object.

The only way to do what you want would be to have a pointer to D[0], but there is no such thing in python.

Upvotes: 2

khelwood
khelwood

Reputation: 59113

When you do ref_D_0=D[0], you make the variable ref_D_0 refer to the same object currently held at D[0].

When you reassign either of those, you are not modifying that object, you are only modifying the variable to refer to a different object.

D[0]=[3,2,1]

Now D[0] and ref_D_0 do not refer to the same object, because you just set D[0] to refer to something else.

If you modify the object instead of just reassiging the variable, e.g.

D[0].append(0)

Then you will be able to see the change reflected in ref_D_0, because then the two variables will still refer to the same object.

Upvotes: 1

Open AI - Opting Out
Open AI - Opting Out

Reputation: 24133

ref_D_0 refers to a particular object.

D[0] refers to the same object.

D[0] = [3, 2, 1] creates a new object and makes D[0] refer to it, replacing the original object.

Of course this doesn't affect ref_D_0. Why should it?

If you want to modify the list instead of replacing it in the dictionary, you can append, insert, or even assign to a slice, e.g. D[0][:] = [3, 2, 1]. This will affect ref_D_0 as they both still refer to the same object.

Upvotes: 2

Related Questions