Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference a dict object?

I have a Python dict object d. d = {'a': 1, 'b': 2, 'c': 3}. My problem is really simple. I want to reference a variable to the elements of d. For example, something like:

In[1]: p = d['a']
>>> p = 1
In[2]: p = 2
In[3]: d
>>> d = {'a': 2, 'b': 2, 'c': 3}

Is that even possible? But as far as I know dict objects are mutable.

like image 791
Bishwajit Purkaystha Avatar asked Jun 04 '26 22:06

Bishwajit Purkaystha


1 Answers

No, this is not possible. After executing the line

p = d['a']

The situation does not look like this:

p  ───>  d['a']  ───>  1

Rather, it looks like this:

 p  ───>  1

          ^
          │
d['a'] ───┘

The name p is bound directly to whatever object was resolved as the value for key 'a'. The variable p knows nothing about the dict d, and you could even delete the dict d now.

like image 157
wim Avatar answered Jun 06 '26 12:06

wim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!