Search code examples
pythonlistmembership

How to test membership of sequence in python list?


I have a dictionary which consists of {str: list}.

What I want to do is find out the keys with specific sequnce that may exist in value.

for example, the content of dictionary is like this:

DOC3187 [1, 2, 3, 6, 7]
DOC4552 [5, 2, 3, 6]
DOC4974 [1, 2, 3, 6]
DOC8365 [1, 2, 3, 5, 6, 7]
DOC3738 [1, 4, 2, 3, 6]
DOC5311 [1, 5, 2, 3, 6, 7]

and I need to find out the keys with sequence of [5,2,3], so desired return should be:

DOC4552, DOC5311

I'm using Python 3.3.2, and the dictionary has about 400 items.


Solution

  • NOTE: I realized that this will actually fail if your list contains [15, 2, 36] which does contain the string 5, 2, 3 so it is just for special cases.

    Since you have a dictionary, maybe list comprehension on the keys and string matching? It is actually the same speed as walking through the elements, according to timeit...

    s_list = [5,2,3]   # sequence to search for
    
    # Setting up your dictionary
    MyD = {'DOC3187' : [1, 2, 3, 6, 7],
        'DOC4552' : [5, 2, 3, 6],
        'DOC4974' : [1, 2, 3, 6],
        'DOC8365' : [1, 2, 3, 5, 6, 7],
        'DOC3738' : [1, 4, 2, 3, 6],
        'DOC5311' : [1, 5, 2, 3, 6, 7]}
    
    query = str(s_list)[1:-1]  # make a string of '5, 2, 3'    
    Matches = [ k for k in MyD if query in str(MyD[k]) ]
    

    Result:

    ['DOC5311', 'DOC4552']