Vladimir Tsyshnatiy Vladimir Tsyshnatiy - 4 years ago 124
Python Question

How can I implement vice versa mapping in Python?

I have to convert a bunch of strings into numbers, process the numbers and convert back.

I thought of a map where I will add 2 keys when I've provided string:

Key1: (string, number);
Key2: (number, string).

But this is not optimal in terms of memory.

What I need to archieve in example:

my_cool_class.get('string') # outputs 1
my_cool_class.get(1) # outputs 'string'

Is there better way to do this in python?

Thanks in advance!

Answer Source

Instead of allocate another memory for the second dict, you can get the key from the value, consider that it will cost you with run-time.

mydict = {'george':16,'amber':19}
print (mydict.keys()[mydict.values().index(16)])

>>> 'george'


Notice that In Python 3, dict.values() (along with dict.keys() and dict.items()) returns a view, rather than a list. You therefore need to wrap your call to dict.values() in a call to list like so:

mydict = {'george':16,'amber':19}
print (list(mydict.keys())[list(mydict.values()).index(16)])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download