## Finding a set in a Dictionary fitting a certain criteria

Question!

I have a dictionary. If V is in DICT[K] then someFunc(k, v) and someFunc(v, k) both return true (and K is in DICT[V]). The dictionary could look like this:

``````{
1: [2, 3, 5],
2: [3, 1, 5],
3: [1, 2],
5: [2, 1],
}
``````

I want to find all sets of numbers of a certain length inside a dictionary that fit this criteria: someFunc(x, y) and someFunc(y, x) must be true for any pair in the dictionary. For example, for the dictionary I showed:

{1, 2, 3} would be a valid length 3 set. The criteria must be valid as all items contain every other item:

• dict[1] contains 2, 3
• dict[2] contains 1, 3
• dict[3] contains 1, 2

What is the best way to find all such sets of a given length in a given dict, if I know that all valid sets must contain a given number.

Answers
``````from itertools import combinations
from collections import OrderedDict

def sf(k,v,d):
return (k in d[v]) and (v in d[k])

def lenN(d, n):
# create a list of unique items
l = list(OrderedDict.fromkeys(i for x in d for i in d[x]))
# collect matching groups
V = list()
for C in combinations(l, n):
for P in combinations(C, 2):
if not sf(P[0], P[1], d): break
else: V.append(C)
return V

d = { 1: [2, 3, 5], 2: [3, 1, 5], 3: [1, 2], 5: [2, 1], }

print lenN(d, 3)
``````

Output

``````[(2, 3, 1), (2, 5, 1)]
``````
By : perreal

This video can help you solving your question :)
By: admin