Search code examples
pythondictionarysearchtuples

Search in dict for a tuple as a key with unknown part


I know that my problem can be solved using simple iteration, but I'm new to python and wonder if there is an 'idiomatic' or standard language construction solution.

So the problem is that I have dictionary like this:

mydict = {
(1,2) : 111,
(2,3) : 222,
(xxx, yyy) : zzz,
(xxx, qqq) : www,
....

It is a dictionary which consist of key-tuples pointing to values How do I search for tuple like (xxx, *) if I need only (xxx, yyy) and (xxx, qqq) pairs? Is there any construction for mydict[(xxx, *)] or something similar?

Thanks for your help!


Solution

  • There isn't a direct language construct for that. You'll have to use a use a list comprehension selecting keys (or values) where the first element of the 2-tuple (x, y) is x:

    lst = [v for (k1, _), v in mydict.items() if k1 == x]