How can I convert the first 2 elements of each array into tuple index?
Current
{0: [1, 1, 0],
1: [1, 2, 357],
2: [1, 3, 167],
3: [1, 4, 155]}
Desired Outcome
{(1, 1): 0,
(1, 2): 357,
(1, 3): 167,
(1, 4): 155}
How can I convert the first 2 elements of each array into tuple index?
Current
{0: [1, 1, 0],
1: [1, 2, 357],
2: [1, 3, 167],
3: [1, 4, 155]}
Desired Outcome
{(1, 1): 0,
(1, 2): 357,
(1, 3): 167,
(1, 4): 155}
You could do it using dictionary comprehension in the following way:
d = {0: [1, 1, 0],1: [1, 2, 357],2: [1, 3, 167],3: [1, 4, 155]}
res = {(v[0],v[1]):v[2] for v in d.values()}
Where res
is:
{(1, 1): 0, (1, 2): 357, (1, 3): 167, (1, 4): 155}
This solution will be problematic if you have duplicate tuples. You should address it in some way.
Loop through the dictionary's values and use tuple unpacking to extract three elements. Pack the first two elements inside a tuple as a key. Assign the last element as a value of the new tuple.
dictionary = {
0:[1,1,0],
1:[1,2,357],
2:[1,3,167],
3:[1,4,155],
}
result = {(j,k):i for j,k,i in dictionary.values()}
or
result = {}
for j,k,i in dictionary.values():
result[(j,k)] = i