Search code examples
pythondefaultdict

Problem with collecting indexes via defaultdict


I’m new to coding and have a problem with my homework. I need to create function which would take some collection as an argument and return dictionary where each element of the collection would be the key and index of element would be the value. I need to use defaultdict to do this.

I understand that I need to loop for elements but I don’t understand what I should use as an argument for defaultdict. Maybe I just don’t understand a concept of defaultdict. Anyway, output should look like this:

d = collect_indexes("hello")

d["h"]

[0]

d["e"]

[1]

d["l"]

[2, 3]

Solution

  • You initialise default dict with the type it should use.

    def collect_indexes(iter):
        ret = defaultdict(list)
        for index, item in enumerate(iter):
            ret[item].append(index)
        return ret