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

Bengt Richter bokr at oz.net
Mon Aug 4 04:17:30 EDT 2003


On Sun, 03 Aug 2003 08:51:40 GMT, "Andy C" <ayc8NOSPAM at cornell.edu> wrote:

>Thanks, looks interesting... but it actually doesn't really address the
>question I was asking.  It doesn't matter since I think the intern solution
I thought it did ;-)

>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.

>effect you do still have a dictionary of the form { 'node1name':
>('node1name', other node1 data), 'node2name': ('node2name', other node2
>data)).  It doesn't seem as silly when you have a real node object, though.
>In my application the nodes are really just strings; I don't need anything
>else.
Well, don't you need the adjacency lists you were talking about? I assumed they were
all lists of out-edges associated with graph vertices. So I defined a Node class
with the two things: a name and an adj_list. You can eliminate the name reference
and just let the graph dict keys be the only reference, but then you will not
so conveniently have the name available to algorithms that process the nodes.
E.g., for some node myNode you might have to search the dict something like
  
    for key,value in graph.items(): # untested!
        if value is myNode: myName=key; break
    else:
        myName = "?? can't find name of %r ??'%myNode

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.

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?)

Anyway, unless I goofed, the { 'node1name':('node1name', other node 1 data) } analogy is
not using two separate strings. It's more like the result of (untested!):

    s = 'node1name'
    graph.update({ s:(s, other node 1 data)}) # pseudo-tuple-element at graph[s][1] ;-)
    del s

To check, I added the assert below, where it scans the node names in the
graph.show() method, and it didn't complain:

    def show(self):
        node_names = self.keys()
        8< snip >8 
        for node_name in node_names:
            assert node_name is self[node_name].name
            prtree(self[node_name])
        ret.append('')
        return '\n'.join(ret)

Regards,
Bengt Richter




More information about the Python-list mailing list