Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to create a dictionary with consecutive numbers for values?

I’m working on a classification task and need to turn a list of labels into one hot outputs for my model. For this i’m trying to find some neat one liner to turn a list of potential labels into a dictionary with values that consecutively ascend. So a simple list like: ['a', 'b', c'] would turn into a dictionary {'a':0, 'b':1, 'c':2}. This is easier for the one hot encoding. So far I’ve tried using the dictionary’s length to do this but I think in line loops get performed before a function because when I try categories = {i:len(categories) for i in labels} it yields all values as 0. I can do it using bigger loops and such but I feel I’m missing some really obvious trick. Thanks in advance.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can do something like this

lst = ['e', 'a', 'b', 'c', 'a', 'b', 'c']
data = {k: i for i, k in enumerate(set(lst))}
print(data)

Output

{'e': 0, 'c': 1, 'a': 2, 'b': 3}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading