Given a list
[0,1,2,3,4,5,6,7,8,9,10,11,12,13]
I would like to label at each of the list position as below
['fir', 'fir', 'sec', 'fir', 'fir', 'fir', 'thr', 'sec', 'fou', 'fou', 'fou', 'thr', 'sec', 'fou']
with respect to a lookup dictionary m
m={ "fir": [0,1,3,4,5],
"sec": [2,7,12],
"thr": [6,11],
"fou": [8,9,10,13]}
Let take for example the first three position.
From the dict m, the position 0 and 1 fell under the key fir. Whereas, the third position (e.g., 2) is under the key sec.
Hence, the list for the three are ['fir', 'fir', 'sec'].
To achieve the above objective, the following is drafted
m={ "fir": [0,1,3,4,5],
"sec": [2,7,12],
"thr": [6,11],
"fou": [8,9,10,13]}
all_key=m.keys()
all_opt=[]
for idx in range (sum(len(v) for v in m.values())):
for nkey in all_key:
if idx in m[nkey]:
all_opt.append(nkey)
break
which produced
opt=['fir', 'fir', 'sec', 'fir', 'fir', 'fir', 'thr', 'sec', 'fou', 'fou', 'fou', 'thr', 'sec', 'fou']
I wonder whether there is better alternative than the nested for-loop?