How can you iterate through a tuple (str), then return a dictionary containing the keys (from the tuple) and the index of the keys as the values?
Input:
tup = ('A', 'A', 'B', 'B', 'A')
Return a dictionary that looks like this:
{'A': [0, 1, 4], 'B': [2, 3]}
>Solution :
Use a defaultdict:
tup = ('A', 'A', 'B', 'B', 'A')
from collections import defaultdict
d = defaultdict(list)
for i,k in enumerate(tup):
d[k].append(i)
dict(d)
or with a classical dictionary:
d = {}
for i,k in enumerate(tup):
if k in d:
d[k].append(i)
else:
d[k] = [i]
output: {'A': [0, 1, 4], 'B': [2, 3]}