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

Python – mapping dictionary keys to string integers avoiding duplicates

I need to create a dictionary in order to do some mapping, like so:

mapping = {x: x.split('_')[0] for x in G}

wich returns:

{'0_cerebellum': '0', '1_cerebellum': '1', '0_cortex': '0', '1_cortex': '1'}

but this will get me duplicates and I need unique string ints as values.

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


Now, once the split class ‘cerebellum’ reaches its last ‘n’ string index (‘1’ here), how do I keep mapping starting from n+1, n+2 (and so on) values for split class ‘cortex’, ending up with:

{'0_cerebellum': '0', '1_cerebellum': '1', '0_cortex': '2', '1_cortex': '3'}

>Solution :

As I understand, this should get your result, using enumerate.

G = ['0_cerebellum', '1_cerebellum', '0_cortex', '1_cortex']
mapping = {key: str(uniqueNum) for uniqueNum,key in enumerate(G)}

Output:

{'0_cerebellum': '0', '1_cerebellum': '1', '0_cortex': '2', '1_cortex': '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