0

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]}
mozway
  • 194,879
  • 13
  • 39
  • 75

2 Answers2

1

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)
mozway
  • 194,879
  • 13
  • 39
  • 75
  • Your second example is very clear in terms of what you're doing. However, is this not a good case for setdefault? – DarkKnight Apr 03 '22 at 19:24
  • 1
    @LancelotduLac you could do something like `for i,k in enumerate(tup): d.setdefault(k, []).append(i)` but I find it a bit cryptic to read. I added a comment – mozway Apr 03 '22 at 19:30
  • Here are some [thoughts on `setdefault` vs `defaultdict`](https://stackoverflow.com/questions/3483520/use-cases-for-the-setdefault-dict-method) – mozway Apr 03 '22 at 19:36
0

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:-

I am creating an empty dictionary.

tup = ('A', 'A', 'B', 'B', 'A')
d = {}

I am 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 its corresponding list in the dictionary

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)
Aarav Jain
  • 21
  • 1
  • 3
  • Have a look at [my answer](https://stackoverflow.com/a/71728838/16343464), you could perform both actions with a single loop. – mozway Apr 03 '22 at 19:18