storing meta data on dictionary keys

Andreas Kraemer akraemer at sbcglobal.net
Wed Oct 10 19:40:22 EDT 2007


On Oct 9, 9:18 pm, Erik Jones <e... at myemma.com> wrote:
> So, do you not keep references to your nodes anywhere but the actual
> graph dict?  I kind of agree with Chris here in that two dicts will
> work. One for the nodes, indexed by their strings.

Yes, I guess that's exactly what I want. To keep things as simple as
possible and not having to keep track of another dictionary. If you
look at class Dict(dict) in the OP, simulating the behavior I'd liked
to have seen for built-in dict itself, the second dictionary is
actually hidden so I don't have to bother with it any more ...

> And, to use the
> actual nodes as keys simply override __hash__ in your Node object
> classes.

The trivial "class Str(str): pass" in the OP (that already inherits
the correct __hash__ and
__eq__) serves the same purpose as your Node(object) below, except
that self.name is stored
in the str built-in, and there is no flashy initializer.

>
>  >>> class Node(object):
> ...     def __init__(self, name, **kwargs):
> ...         self.name = name
> ...         for k, v in kwargs.items():
> ...             self.__dict__[k] = v
> ...
> ...     def __hash__(self):
> ...         return hash(self.name)
> ...
>  >>> nodes = {}
>  >>> graph = {}
>  >>>
>  >>> n = Node('foo')
>  >>> m = Node('blah', baz=5)
>  >>>
>  >>> nodes[n.name] = n
>  >>> nodes[m.name] = m
>  >>>
>  >>> for name, node in nodes.items():
> ...     graph[node] = "whatever for node %s" % name
> ...
>  >>> nodes{'blah': <__main__.Node object at 0x76c50>, 'foo':
> <__main__.Node object at 0x76d30>}
>  >>> graph{<__main__.Node object at 0x76c50>: 'whatever for node
> blah', <__main__.Node object at 0x76d30>: 'whatever for node foo'}
>  >>> graph[nodes['foo']]'whatever for node foo'

I still believe that it would be a nice-to-have, and probably only a
small effort to equip
the built-in dict with a get_key() method. The whole mechanism of
dictionary look-up in Python,
based on "duck typing", and only caring about the __hash__ and __eq__
methods supplied by
the key object, is constructed in a way that allows objects inserted
into the dictionary as keys
and objects used for look-up to be (non-trivially) distinct.
Therefore, it would actually be
nice to be able to retrieve keys from the dict in a direct way (other
than via .keys()).
The same may apply to sets and frozensets as well ...;-)




More information about the Python-list mailing list