pythonalgorithmdata-structures

# Generate list of pattern contained in dictionary values Python

I have the following dictionary as an input of a Python script:

``````d = {
'A':[[1,2,7]],
'B':[[1,3,7], [1,3], [1,7]],
'C':[[1,3,7], [2,6]],
'D':[[1,3,2], [2,1,3]]
}
``````

and I want the following patterns as outputs:

``````{
(2,7):['A'],
(3,7):['C'],
(2,6):['C'],
(2,3):['D'],
(1,2):['A','D'],
(1,7):['A','B','C'],
(1,3):['B','C','D']
}
``````

in which the resulting values should be generated considering the existence of a pair of indices in the values of the dictionary d.

For instance the pair (1,3) exists in the sublists of the values 'B', 'C', and 'D'

``````'B':[[1,3,X]],
'C':[[1,3,X]],
'D':[[1,3,X], [X,1,3]]
``````

and the pair (2,7) exists only in the sublist of the key 'A'

Solution

• Try:

``````from itertools import combinations

d = {
"A": [[1, 2, 7]],
"B": [[1, 3, 7], [1, 3], [1, 7]],
"C": [[1, 3, 7], [2, 6]],
"D": [[1, 3, 2], [2, 1, 3]],
}

out = {}
for k, v in d.items():
for subl in v:
for c in combinations(subl, 2):

print(out)
``````

Prints:

``````{
(1, 2): {"D", "A"},
(1, 7): {"B", "C", "A"},
(2, 7): {"A"},
(1, 3): {"B", "D", "C"},
(3, 7): {"B", "C"},
(2, 6): {"C"},
(2, 3): {"D"},
}
``````