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

Viewed 1998

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 construcion 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 wich 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!

2 Answers

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]

You could do that by breaking it down a step further and grouping all xxx, ??? together in the same level in the dictionary, instead of your tuple approach for the keys.

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

This kind of gets you to the same spot that you want to be at because mydict[xxx] = { yyy : zzz, qqq : www}, which you can take a step further and do mydict[xxx].values() to get you an array mydict[xxx].values = [zzz, www], an array of the values that contain xxx in the key.

Related