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

Andy C andychup at
Fri Aug 1 02:36:41 CEST 2003

I am new to python, so please bear with me if I am making some
conceptual error.

Basically I want to create a graph with an adjacency list
representation, but I don't want any of the adjacency lists to have
duplicate strings when it is avoidable.  I have a function createEdge
that adds an edge to the graph.  The arguments will be distinct since
they are read from text files.  But basically I want to use the
dictionary as a string pool, and if the argument string equals
something in the pool already, don't use the argument string, just a
use a reference to something in the string pool already.

Is this a waste of time?  Because I know in python I cannot be certain
that the argument strings that are read from files are even garbage
collected anyway.  I could certainly do the job with duplicate
strings, but it would seem wasteful.  I am a C programmer, and old
habits die hard.

The following code works -- I tested it and entries in the adjacency
list that are equivalent are in fact identical.  But it seems rather
stupid to have a dictionary of the form {'alice': 'alice', 'bob':
'bob'}, etc.  i.e. the keys and values are the same.  It would be nice
if I can get a reference to the key in the same time as a hash lookup.
 I know I can do dictionary.keys().index( 'string' ) or something but
that would be pretty inefficient, I believe.

class GraphAccumulator:
    def __init__( self, fileFunction ):
        self.fileFunction = fileFunction
        self.adjList = {}                       # adjacency list
        self.nodes = {}                         # list of nodes for
preventing string dupes

    def createEdge( self, node1, node2 ):

        # another way of doing by using a dictionary

        nodes = self.nodes
        if nodes.has_key( node2 ):
            node2 = nodes[ node2 ]            
            nodes[ node2 ] = node2            

        adjList = self.adjList            
        if adjList.has_key( node1 ):
            adjList[ node1 ].append( node2 );
            adjList[ node1 ] = [ node2 ];       # singleton edge list

More information about the Python-list mailing list