Home > database >  Python - mapping dictionary keys to string integers avoiding duplicates
Python - mapping dictionary keys to string integers avoiding duplicates

Time:02-13

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.


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'}

CodePudding user response:

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'}

CodePudding user response:

use enumerate():

>>> l = ['test', 'foo', 'None', 'Bar']
>>> enumerate(l)
<enumerate object at 0x00000258DE241340>
>>> list(enumerate(l))
[(0, 'test'), (1, 'foo'), (2, 'None'), (3, 'Bar')]

this is your finally code:

mapping = {x: str(i) for i, x in enumerate(G)}
  • Related