Can dictionary values access their keys?

Matthew Thorley ruach at chpc.utah.edu
Fri Apr 8 13:55:52 EDT 2005


Scott David Daniels wrote:
> Matthew Thorley wrote:
> 
>> This may be a very rudimentary question, but here goes:
> 
> From your questions, I believe you are not thinking of values as
> being distinct from the names and data structures that refer to them.
> 
> What is the parent of 23 in the following expression?
> 
>     1 + 11 * 2
> 
> If you know that, what is the parent of 293 in the same expression?
> 
>> If I have a simple dictionary, where the value is a class or function,
>> is there an interface through which it can discover what its key is?
>> Similar to index() for list.
> 
> 
>     def keyfor(dictionary, element):
>         for key, value in dictionary.iteritems():
>             if value == element:  # value is element if identity quest
>                 return key
>         raise ValueError, element
> 
>> On a similar note, if one object is part of another, 
> 
> This is the idea you have wrong.  In C, C++, Java, and Fortran you
> might have objects part of other objects, but in Python objects refer
> to each other.
> 
> How about this:
> 
>     class Holder(object): pass
> 
>     v = [1 + 11 * 2]
>     w = [1, v, 3]
>     d = {1: v}
>     o = Holder()
>     o.x = v
> 
> What is the parent of v?
> 
> Or even worse:
> 
>     v = [1]
>     v[0] = v
> 
> What is the parent of v now?
> 
> --Scott David Daniels
> Scott.Daniels at Acm.Org

I see what your saying, but I my situation the values of the dictionary
are unique objects created by a parent object. Sorry :(, I didn't
explain that very well in my first post.

When the 'root object' is 'global' I see what your saying, but when

class A:
  def __init__(self, container):
    self.container=container

class B(dict):
  def magice_get_parent(self):
     ...

class special_value():
  def __init__(self, val):
     self.val = val

  def magic_get_key(self):
    ...

parent = A(B)
parent.container[x] = special_value(1)
parent.container[y] = special_value(2)
parent.container[z] = special_value(1)


In this example, in my mind, the following should happen, and in theory
using introspecition, actualy possible.

child = parent.container
D.magic_get_parent() #returns parent


value1 = parent.container[x]
value2 = parent.container[y]
value3 = parent.container[z]

value1.magic_get_key() #returns x
value2.magic_get_key() #returns y
value3.magic_get_key() #returns z

Let me know if I'm nutz!
--Matthew




More information about the Python-list mailing list