How do I get a reference to a KEY value of a dictionary?
Andy C
ayc8NOSPAM at cornell.edu
Sat Aug 2 06:05:17 EDT 2003
I don't see how I can do this and let me eliminate duplicates. I need to
assign the old duplicate string to the unique string that already exists.
Hence the question, how do I get a reference to the KEY value? I know I can
use keys() and do a linear search, but that is much more inefficient. I
would like to get a reference to the key value in the same time that it
takes to do a hash lookup (constant time).
Basically I would want to rewrite this section of the code I posted:
nodes = self.nodes
if nodes.has_key( node2 ):
node2 = nodes[ node2 ]
else:
nodes[ node2 ] = node2
This dictionary seems stupid, I agree. The keys and values are the same.
But in the first part of the if, I want to reassign node2 to an equivalent
string that already exists. How can I do that?
The intern solution seems reasonable, and it appears that it was designed
specifically for this problem. I wasn't aware of the implementation
problems. But I'm still curious about different ways to do it.
> That makes some sense, but why use the string object for both key and
> value? Just do
>
> d[key] = True
>
> You could optimize your coding style (if not your speed) in Python 2.3
> by using sets. I'd recommend against using intern(), because in Python
> 2.2 and earlier, interned strings *never* get garbage collected. Even
> in Python 2.3, you may end up with worse memory behavior.
> --
> Aahz (aahz at pythoncraft.com) <*>
http://www.pythoncraft.com/
>
> This is Python. We don't care much about theory, except where it
intersects
> with useful practice. --Aahz
More information about the Python-list
mailing list