I am maintaining a dictionary that keeps track of the similarities between pairs of objects.
For example, this dictionary could look like this:
similarities = {
p1: {p2: v12, p3:v13, p4:v14},
p2: {p1: v21, p3:v23, p4:v24},
p3: {p1: v31, p2:v32, p4:v34},
p4: {p1: v41, p2:v42, p4:v43}
}
Note, that the similarity measurement is symmetric. Therefore, similarities[p1][p2]
is the same as similarities[p2][p1]
i.e. v12 == v21
.
Sometimes, I'll need to eliminate p2
from similarities[p1]
; and in doing so, I'll need to remove p1
and p2
from all the inner dictionaries in similarities
as well.
This is tedious and inefficient.
So instead of maintaining a symmetric dictionary, is there a way to maintain a dictionary with a composite key so that I can lookup similarities[p1,p2]
?
I can't really use a tuple
since (p1, p2) != (p2, p1)
and I can't know a priori how to order the tuple.
A frozenset
is the only other container that I can think of, but that won't cut it since there may still be other keys in similarities
that contain either p1
or p2
as a component. So what container could I use to solve this issue?
Technical info:
- python 2.7
- there will always be exactly 2 elements in this "composite key"
Thank you