0
votes

I am trying to create a dictionary where values are obtained from iterating a list. The keys are in the tuple format (i,j).

e.g. if i = 3, j = 3, the keys are

(1,1), (1,2), (1,3), (2,1), (2,2), (2,3), (3,1), (3,2), (3,3).

If my list is as follows,

lst = list(range(1, 10))

How do I obtain a dictionary like this?

{(0, 0): 1, (0, 1): 2, (0, 2): 3, (1, 0): 4, (1, 1): 5, (1, 2): 6, (2, 0): 7, (2, 1): 8, (2, 2): 9}

I have tried:

dict = {(i,j): d for d in lst for i in range(1, i+1) for j in range(1, j+1)}

but the values of my dictionary are strictly the last value of lst. This is my output instead:

>>> {(0, 0): 9, (0, 1): 9, (0, 2): 9, (1, 0): 9, (1, 1): 9, (1, 2): 9, (2, 0): 9, (2, 1): 9, (2, 2): 9}

1
If the value of each dictionary entry is calculated from the key, could you clarify the relationship between the key and the value or how the value is calculated? - Kelo
@Kelo The first value of the list corresponds to (0,0), the second value corresponds to (0,1), third to (0,2)..... Basically in this format (i,j). I'm sorry I have trouble explaining this theoretically. - MrSoLoDoLo

1 Answers

2
votes

If you already have your list of tuples, list_of_tuples, then this would work:

d = {L:i for i,L in enumerate(list_of_tuples)}

or if a separate list of length len(list_of_tuples) exists, called lst, then you could do

d = {L:lst[i] for i,L in enumerate(list_of_tuples)}