'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}
which 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'}
Solution 1:[1]
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)}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Delta |
