wildcolor
wildcolor

Reputation: 574

check if part of my dict/struct is in list [python]

My list is like below:

list = [{'a', 'b', 1}, {'x', 'y', 2}]

I have my variables and I only want to match the first 2 letters.

aa = {'x', 'y', 2}
bb = {'x', 'z', 2}

So, aa in list is True but bb in list is False.

I've tried to use {'x', 'y', _} in list. But this sometimes return True and sometimes False? This might because the letters are not in order, because when I print list, I see the letters are actually in random order? Any help please?

Upvotes: 0

Views: 102

Answers (2)

Maikflow
Maikflow

Reputation: 191

Using a function:

def compare_sequences(main_sequence=None, compared_sequence=None, elements=2):
    for seq in main_sequence:
        if compared_sequence[:elements] == seq[:elements]:
            return True 
    return False

my_tuples = (('a', 'b', 1), ('x', 'y', 2))
aa = ('x', 'y', 2)
bb = ('x', 'z', 2)
print(compare_sequences(my_tuples, aa, 2))

True

Upvotes: 0

mhawke
mhawke

Reputation: 87124

I'm pretty sure that you mean to be working on lists or tuples, not sets, so you can use an itemgetter here:

from operator import itemgetter

first_two = itemgetter(0, 1)

l = [['a', 'b', 1], ['x', 'y', 2]]    # list of lists
aa = ['x', 'y', 2]
bb = ['x', 'z', 2]
cc = ('a', 'b', 100)

>>> first_two(aa) in (first_two(x) for x in l)
True
>>> first_two(bb) in (first_two(x) for x in l)
False
>>> first_two(cc) in (first_two(x) for x in l)
True

first_two is an itemgetter that will return a tuple containing the corresponding elements from the given sequence. This is applied to each item in the list l with a generator expression, extracting the first two elements of each item in the list. Similarly the first two elements of each variable (aa, bb, etc) are extracted. The resulting tuples are then compared to get a boolean result.

You could generalise this into a function:

def part_in(value, sequence, getter=None):
    if getter is None:
        getter = itemgetter(*range(len(value)))    # compare on all items
    return getter(value) in (getter(x) for x in sequence if len(x) >= len(value))

>>> part_in(aa, l)
True
>>> part_in(aa, l, itemgetter(0, 1))
True
>>> part_in(aa, l, itemgetter(0, 2))    # considers first and third items only
True

The last example shows that it's easy to select and compare any set of indices for the items.

Upvotes: 2

Related Questions