I would like to save some data in Python in a similar form with a dictionary: {1:'a', 2:'b'} . Each value will be unique, not only among other values, but also among keys.
Is there a simple data structure that I can use to get the corresponding object, regardless of whether I ask using the "key" or "value"? For example:
>>> a = {1:'a', 2:'b'} >>> a[1] 'a' >>> a['b'] 2 >>> a[3] KeyError
"Keys" are standard python collections; values ββare short (<256char) strings.
My current solution is to create a reverse dictionary and search for it if I cannot find the 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 is not very convenient (my dictionaries can be up to several hundred megabytes) and an average of 50% slower.
EDIT: as mentioned in several answers, the two dicts do not use dual memory usage, as this is only a dictionary, not elements inside, i.e. duplication.
Is there a solution to improve this?
python dictionary hashtable
Alex j
source share