Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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.


Solution 2:

As others have pointed out, this is not really possible in Python, it doesn't have C++ style references. The closest you can get is if your dictionary value is mutable, then you can mutate it outside and it will be reflected inside the dictionary (because you're mutating the same object as the object stored in the dictionary). This is a simple demonstration:

>>> d = {'1': [1, 2, 3] }
>>> d
{'1': [1, 2, 3]}
>>> x = d['1']
>>> x.append(4)
>>> d
{'1': [1, 2, 3, 4]}

But in general, this is a bad pattern. Don't do this if you can avoid it, it makes it really hard to reason about what's inside the dictionary. If you wanna change something in there, pass the key around. That's what you want.


Solution 3:

Not always, but if the associated dictionary value is something mutable, such as a list, you can effectively create a pointer to it if you're using the CPython interpreter by using the built-in id() function coupled with its inverse, as shown below:

import _ctypes

def di(obj_id):
    """ Inverse of id() function. """
    return _ctypes.PyObj_FromPtr(obj_id)

d = {'a': [1], 'b': 2, 'c': 3}
print(d)  # -> {'a': [1], 'b': 2, 'c': 3}
p = id(d['a'])
di(p)[0] = 42
print(d)  # -> {'a': [42], 'b': 2, 'c': 3}

Post a Comment for "How To Reference A Dict Object?"