Search code examples
pythondictionaryhashtable

Reversible dictionary for python


I'd like to store some data in Python in a similar form to a dictionary: {1:'a', 2:'b'}. Every value will be unique, not just among other values, but among keys too.

Is there a simple data structure that I can use to get the corresponding object no matter if I ask using the 'key' or the 'value'? For example:

>>> a = {1:'a', 2:'b'}
>>> a[1]
'a'
>>> a['b']
2
>>> a[3]
KeyError

The 'keys' are standard python ints, an the values are short (<256char) strings.

My current solution is creating a reversed dictionary and searching it if I can't find a result in the original dictionary:

pointsreversed = dict((v, k) for k, v in points.iteritems())
def lookup(key):
    return points.get(key) or pointsreversed.key()

This uses twice as much space, which isn't great (my dictionaries can be up to a few hundred megs) and is 50% slower on average.

EDIT: as mentioned in a few answers, two dicts doesn't double memory usage, as it's only the dictionary, not the items within, that is duplication.

Is there a solution that improves on this?


Solution

  • Related posts:

    Python mapping inverse

    Python 1:1 mappings

    Of course, if all values and keys are unique, couldn't you just use a single dictionary, and insert both key:value and value:key initially?