How do I get a reference to a KEY value of a dictionary?

Andy C ayc8NOSPAM at
Tue Aug 5 05:31:27 CEST 2003

> >is fine for me.  But if I'm not mistaken, your solution still stores the
> >node names in the values of the dictionary (via the Node objects).  So in
> No, just references, not duplicate strings.

OK, you're right -- I assumed that the key and value were duplicated, but
that's not the case.  I don't know why I thought that, maybe since the key
must be immutable and the value is mutable.  So I guess having a dictionary
of the form { 'A': 'A', 'B': 'B' } is not as stupid as it first seems, since
only a reference is stored.  But still I wonder why the language doesn't
have a facility for getting a reference to the key value in constant time.
Apparently someone did it by modifying the C source for the dictionary to
add a ref_key() accessor.  It seems like it would be useful quite often.

> One caveat though, if your graph has cycles, changing the adjacency lists
to direct node
> references instead of names will create reference cycles that may have to
be broken for
> the gc. I have to look into that. You can comment that fixup loop out if
you want to
> keep adjacency lists as name string references instead of node references.

Good point... I thought though that the new python (2.3?) will GC data with

> BTW, have you looked at the sets module of 2.3? That would let you have a
set of strings
> with no associated values, and no duplicates (but how do you represent
adjacency lists then?)

Actually, I did run across the sets type recently.  It is actually built *on
top of* dict, so it's no better.  Ex:

>>> a = Set([1,2,3])
>>> a
Set([1, 2, 3])
>>> a._data
{1: True, 2: True, 3: True}

It just stores a dummy value as the value of the dict.

BTW I am using a regular dictionary for the adjacency list, with the list of
destination edges.  I was using another dictionary for the 'cache' of names.

Thanks for the help.


More information about the Python-list mailing list