Clean python code to get a reverse mapping
When working with machine learning problems, often I use python dictionary to map categorical values to its integer encoded values. Something like:
import string
feature_encoder = {v:i for i, v in enumerate(string.ascii_lowercase)}
To get back the original value, I need to have a reverse mapping, I used to create it with:
feature_decoder = {v:k for k, v in feature_encoder.items()}
This is fine, but I dislike it for that I have to spend some mental effort to read it to know what I was doing the next time I read my code. And today I found a nicer way to get the reverse mapping.
feature_decoder = dict(map(reversed, feature_encoder.items()))
It is doing exactly the same thing, but I can just read it as an English sentence to know what is going on.