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.
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)}
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)}}
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)}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With