简体   繁体   中英

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?

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]}

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM