Python: does a pointer pointer store a key value?

I am wondering if there is a built-in way to do this ... Take this simple code for example:

D = {'one': objectA(), 'two': objectB(), 'three': objectC()}
object_a = D['one']

      

I believe it object_a

just points to the objectA()

one created on the first line and doesn't know anything about the dictionary D

, but my question is, does Python store the key of the dictionary value? Is there a way to get the key 'one'

if all you have is a variable object_a

(without skewing over the dictionary, of course)?

If not, I can store the value 'one'

internally objectA()

, but I'm just wondering if Python already stores this information.

+2


source to share


4 answers


I think not.



Consider the case of adding one object to a (large) number of different dictionaries. It would be quite expensive for Python to keep track of this for you, it would be expensive for a feature not used by most.

+7


source


The mapping is dict

not trivially "reversible" as you describe.

  • The key must be immutable. It must be immutable so that it can be hashed for lookups and not tolerate spontaneous changes.

  • The value does not have to be constant, it is not hashed for fast lookups.



You can't just go from value back to key without (1) creating an immutable value and (2) filling in some other kind of mapping with key mapping "reverse" value →.

+3


source


Is there a way to get the key "one" if all you have is the variable object_a (no dictionary weaving, of course)?

No, Python does not impose such useless redundancy on you. If objA

the factory is callable:

d = {'zap': objA()}
a = d['zap']

      

and

b = objA()

      

as well as

L = [objA()]
c = L[0]

      

everything leads to exactly the same types of references in a

, b

and c

, to exactly equivalent objects (if that's what objA

gives you in the first place), without one wasted bit (not in the objects mentioned or in any redundant and completely hypothetical auxiliary structure) to write "this / was the value in the list L and / or dict d in this index / key" ((or there have been many indexes / keys since then)).

+2


source


As others have said, there is no built-in way to do this as it takes up memory and is not usually required.

If not, I can store the value "one" inside the A () object, but I'm just wondering if Python already stores this information.

Just wanted to add that it's pretty easy to add a more general solution that will do this automatically. For example:

def MakeDictReversible(dict):
 for k, v in dict.iteritems():
  v.dict_key = k

      

This function simply inserts each object into the dictionary using the "dict_key" element, which is the dictionary key used to store the object.

Of course, this code can only run once (ie run it on two different dictionaries that share the object, and the object's "dict_key" element will be overwritten by the second dictionary).

0


source







All Articles