Getting the indexes of each element in a list of lists and making a dictionary

arthionne :

I am trying to create a dictionary where the keys are elements of each list, and the values are their indexes in that list of lists, so that I can easily find where exactly every element is.

So if the list is [['a', 'a', 'b'], ['a', 'b', 'b'], ['c', 'c', 'c']] ,

dictionary should be like this:{'c': {(2, 0), (2, 1), (2, 2)}, 'b': {(1, 1), (1, 2), (0, 2)}, 'a': {(0, 1), (1, 0), (0, 0)}}

I can get each elements index in their respective lists with list comprehension: final_list = [list(enumerate(i)) for i in mylist] but I couldn't find a way to get their "complete" indexes that also include the index of their list.

Riccardo Bucco :

Here is a simple solution:

input = [['a', 'a', 'b'], ['a', 'b', 'b'], ['c', 'c', 'c']]

result = {}
for i, lst in enumerate(input):
    for j, element in enumerate(lst):
        if element in result:
            result[element].add((i, j))
        else:
            result[element] = {(i, j)}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=193235&siteId=1