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]}
CodePudding user response:
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]}
You could also use dict.setdefault
, although I find it not very explicit if you are not familiar with the setdefault
method:
d = {}
for i,k in enumerate(tup):
d.setdefault(k, []).append(i)
CodePudding user response:
A simple approach would be to assign an empty list to each unique element in the tuple. Then append the index of each element in the corresponding list.
Here is my code:-
Creating an empty dictionary.
tup = ('A', 'A', 'B', 'B', 'A')
d = {}
Assigning an empty list in the dictionary to each unique element in the tuple.
for i in range(len(tup)):
d[tup[i]] = []
Appending the index of each element of the tuple in it's correspondind list in the dictonary
for j in range(len(tup)):
d[tup[j]].append(j)
The complete code:-
tup = ('A', 'A', 'B', 'B', 'A')
d = {}
for i in range(len(tup)):
d[tup[i]] = []
for j in range(len(tup)):
d[tup[j]].append(j)
print(d)