Reputation: 353
I am trying to find any permutation of a list inside another Dictionary with tuples.
For example, what would be the best way to find any combination of [1,2,3]
inside of a Dictionary which is formatted like this: {(1,3,2):'text',(3,1,2):'text'}
.
The only matches that would qualify for [1,2,3]
would be (1,2,3),(1,3,2),(2,1,3),(2,3,1),(3,2,1),(3,1,2)
.
Matches that wouldn't qualify include Lists that don't contain all of the items (For example: (1,2)
or (2)
), and matches that contain extra items (for example:(1,2,3,4)
or (2,3,7,1)
).
Upvotes: 0
Views: 72
Reputation: 1124090
Use itertools.permutations()
to generate all permutations of a list:
from itertools import permutations
if any(tuple(perm) in yourdictionary for perm in permutations(yourlist)):
# match found
but you really want to rethink your data structure. If you made your keys frozenset()
objects instead, you simply would test for:
if frozenset(yourlist) in yourdictionary:
# match found
which would be a lot faster.
Demos:
>>> from itertools import permutations
>>> yourdictionary = {(1,3,2):'text',(3,1,2):'text'}
>>> yourlist = [1, 2, 3]
>>> print any(tuple(perm) in yourdictionary for perm in permutations(yourlist))
True
>>> yourdictionary = {frozenset([1, 2, 3]): 'text', frozenset([4, 5, 6]): 'othertext'}
>>> frozenset(yourlist) in yourdictionary
True
>>> frozenset([2, 3]) in yourdictionary
False
Upvotes: 2