Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading