Possible Duplicate:
Efficient bidirectional hash table in Python?
I'm working on an AST parser, that parses python code. First, I turn the python code into an AST with a call to compile
.
In doing this, I need to ensure that I don't compile the same imported module twice, even if there are two calls to import it.
Currently, I can detect that these two calls are equivalent:
import modname as mod
import modname as mod
I maintain a dictionary that maps (in this case) mod
to modname
. I use this not only to detect that modname
has already been imported, but also for some other bookkeeping functions down the road.
Now, I can't detect that the following three calls import the same module:
import modname as mod
import modname as foo
import modname
I know that I can easily circumvent this problem by using a set
to contain modname
and check this set before I compile modname
the second time. However, this requires another block of linear space.
I could do a linear pass over the dictionary to check if any key maps to a value of modname
, but that defeats the purpose of using a dict.
Hence my question: does there exist a data structure that's a "two-way dict
" - one that maps it's keys to values and whose values can be looked up at O(1) time as well?