Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return the value for a dictionary key (tuple), irregardless of order of the tuple elements

I have a dictionary where the keys are tuples:

submatrix = {('W', 'F'): 1, ('L', 'R'): -2, ('S', 'P'): -1,...}

To dictionary contains half of a symetric matrix, and the following are equivalent

('W', 'F'): 1
('F', 'W'): 1

I want to return the value for a given tuple, irregardless of order. this fails if order of elements of tuple are not matched:

for i in range(1,len(y)+1):
   for j in range (1,len(x)+1):
        if(submatrix[(x[j-1], y[i-1])]):

I also tried:

   if(submatrix[(x[j-1], y[i-1])] or submatrix[(y[j-1], x[i-1])])

and this failed

Charles

like image 974
Charles Hauser Avatar asked Jan 25 '26 23:01

Charles Hauser


1 Answers

Convert your keys to frozensets:

submatrix = {('W', 'F'): 1, ('L', 'R'): -2, ('S', 'P'): -1}

d = {frozenset(k): v for k, v in submatrix.items()}

d[frozenset({'W', 'F'})]  # 1
d[frozenset({'F', 'W'})]  # 1

This works because frozensets are immutable and unordered.

like image 121
jpp Avatar answered Jan 27 '26 13:01

jpp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!