Can dictionary values access their keys?

Bengt Richter bokr at oz.net
Fri Apr 8 15:59:02 EDT 2005


On Fri, 08 Apr 2005 09:30:25 -0600, Matthew Thorley <ruach at chpc.utah.edu> wrote:

>This may be a very rudimentary question, but here goes:
>
>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.

You can make a reverse dictionary, if the key:value pairs are unique and
the values are hashable. But I doubt this is the real solution to your real problem.

 >>> def foo(): pass
 ...
 >>> def bar(): pass
 ...
 >>> dct = dict(fookey=foo, barkey=bar)
 >>> dct
 {'barkey': <function bar at 0x0301410C>, 'fookey': <function foo at 0x03014064>}
 >>> revdict = dict((v,k) for k,v in dct.items())
 >>> revdict[foo]
 'fookey'
 >>> revdict[bar]
 'barkey'
 >>> class Baz(object): pass
 ...
 >>> dct['bazkey'] = Baz
 >>> dct
 {'barkey': <function bar at 0x0301410C>, 'fookey': <function foo at 0x03014064>, 'bazkey': <class '__main__.Baz'>}
 >>> revdict = dict((v,k) for k,v in dct.items())
 >>> revdict[Baz]
 'bazkey'


But if you had

    d = {'key1':foo, 'key2':foo}

What would foo's key be?

>
>For a list, assuming I new what the parent list was I could do something
>like this.
>
>>>> class child:
>...     def get_parent_index(self, parent):
>...             return parent.index(self)
>...
>>>> a = child()
>>>> l = [a]
>>>> b = l[0]
>>>> b.get_parent_index(a)
>>>> b.get_parent_index(l)
>0
>
>Is there a way to do something like that with dicts?
>
>
>On a similar note, if one object is part of another, is there a way for
>the 'child' obj to discover what/who the 'parent' object is? That way
>parent does not have to be explicityly passed to get_parent_index?
>
Any number of "parents" can refer to a given obj, so even if you
have a context where you can search successfully, you may find many "parents"
-- unless you can guarantee 1:1 as in the dct/revdict example above.

>The idea is like this:
>
>>>> class child:
>...     def get_parent_index(self):
>		parent = self.magic_parent_discovery()
>...             return parent.index(self)
>...
>
I would suggest thinking about defining a class for the graph you are concerned with
and giving it methods to add children to nodes, and automatically maintain the
parent references as you walk your graph and add or delete nodes. Then you should
easily be able to define more methods to get various info as you may want.
Properties may interest you too, giving you a way to convert plain object attributes
to dynamically computed attributes without chaninging the code that refers to the attribute.

Unless you have a huge graph, I wouldn't worry about the space. If you bump into
limitations, try __slots__ for node attributes. But if you know now that it's going
to be huge, describe your (real) problem now for better help.

Regards,
Bengt Richter



More information about the Python-list mailing list