I have a dictionary that maps 3tuple to 3tuple where key-tuples have some element in common
dict= { (a,b,c):(1,2,3),
(a,b,d):tuple1,
(a,e,b):
You could reconstruct your dictionary into a triply nested dict.
dict= { ("foo", 4 , "q"): 9,
("foo", 4 , "r"): 8,
("foo", 8 , "s"): 7,
("bar", 15, "t"): 6,
("bar", 16, "u"): 5,
("baz", 23, "v"): 4
}
d = {}
for (a,b,c), value in dict.iteritems():
if a not in d:
d[a] = {}
if b not in d[a]:
d[a][b] = {}
d[a][b][c] = value
Here, d is equivalent to:
d = {
"foo": {
4:{
"q": 9,
"r": 8
},
8:{
"s": 7
}
},
"bar":{
15:{
"t": 6
}
16:{
"u": 5
}
},
"baz":{
23{
"v": 4
}
}
}
Now you can easily iterate through the possible third keys, given the first and second.
#find all keys whose first two elements are "foo" and 4
a = "foo"
b = 4
for c in d[a][b].iterkeys():
print c
Result:
q
r
This only works for matching the third key. For instance, you wouldn't be able to find all second keys, given the third and the first.