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
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.
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