Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 491
arty Avatar asked Mar 10 '20 15:03

arty


3 Answers

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)}
like image 144
Riccardo Bucco Avatar answered Oct 12 '22 12:10

Riccardo Bucco


you can use:

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

result = {}
for i, e in enumerate(l):
    for j, x in enumerate(e):
        result.setdefault(x, set()).add((i, j))
print(result)

output:

{'a': {(0, 0), (0, 1), (1, 0)},
 'b': {(0, 2), (1, 1), (1, 2)},
 'c': {(2, 0), (2, 1), (2, 2)}}
like image 21
kederrac Avatar answered Oct 12 '22 13:10

kederrac


You can do it like this:

res = {}
for i, l in enumerate(var):
    for j, letter in enumerate(l):
        res[letter] = res.get(letter, set()) | {(i, j)}

res

# {'a': {(0, 0), (0, 1), (1, 0)},
#  'b': {(0, 2), (1, 1), (1, 2)},
#  'c': {(2, 0), (2, 1), (2, 2)}}
like image 42
zipa Avatar answered Oct 12 '22 13:10

zipa