A data-structure for 1:1 mappings in python?

The other alternative is to make a new
class which unites two dictionaries,
one for each kind of lookup. That
would most likely be fast but would
use up twice as much memory as a
single dict.

Not really. Have you measured that? Since both dictionaries would use references to the same objects as keys and values, then the memory spent would be just the dictionary structure. That’s a lot less than twice and is a fixed ammount regardless of your data size.

What I mean is that the actual data wouldn’t be copied. So you’d spend little extra memory.

Example:

a = "some really really big text spending a lot of memory"

number_to_text = {1: a}
text_to_number = {a: 1}

Only a single copy of the “really big” string exists, so you end up spending just a little more memory. That’s generally affordable.

I can’t imagine a solution where you’d have the key lookup speed when looking by value, if you don’t spend at least enough memory to store a reverse lookup hash table (which is exactly what’s being done in your “unite two dicts” solution).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)