0

I have

x = [
    {"foo": "bar"},
    {"bar": "baz"},
]
y = [
    {"bar": "baz"},
    {"foo": "bar"},
]

for item in (x, y):
    match item:
        case [{"foo": "bar"}, *other_items]:
            print(f"Caught {item}")
        case _:
            print(f"Did not catch {item}")

This yields the following output:

Caught [{'foo': 'bar'}, {'bar': 'baz'}]
Did not catch [{'bar': 'baz'}, {'foo': 'bar'}]

Is there a way to redefine the pattern [{"foo": "bar"}, *other_items] so to catch the value for both x and y?

Please note that I would really like to use pattern matching to solve this problem.

fredrik
  • 9,631
  • 16
  • 72
  • 132
  • just loop over `item` and match for `{"foo": "bar"}`? – juanpa.arrivillaga Nov 04 '22 at 17:47
  • @juanpa.arrivillaga yeah, but that is not what I am asking for. I'm trying to solve this problem by changing the pattern, if at all possible. – fredrik Nov 04 '22 at 17:48
  • 1
    The "pattern" semantically would be "{"foo": "bar"} anywhere in the list", if I'm understanding correctly? I don't think pattern matching can do that, but I'm not sure – juanpa.arrivillaga Nov 04 '22 at 17:49
  • Yeah, that's exactly what I would like to do - but I'm also thinking it might not be possible at all, hence my question here. :) – fredrik Nov 04 '22 at 17:50
  • 1
    Does this answer your question? [Is there a way to test if an Iterable contains a pattern using python's "match" statement?](https://stackoverflow.com/questions/67636684/is-there-a-way-to-test-if-an-iterable-contains-a-pattern-using-pythons-match) – dermen Nov 04 '22 at 20:11

0 Answers0