Question

I have a python dictionary that I have build where its key is a tuple and values are in a list. Tuple contains integer and string. To best describe here is a simple example:

>>> x = {(1, 'test'): ['marry', 'tom']}

I want to build a logic if first element of the tuple in the dictionary key exist do my logic:

so I tried following:

>>> if 1 in x:
...     print x
... 

and it didn't work.

But then i did the following to test if in function work when the key is not a tuple and it does:

>>> y = {}
>>> y[1] = []
>>> y[1].append("tom")
>>> if 1 in y:
...     print y
... 
{1: ['tom']}

How can check if the key exist in a dictionary if key happened to be first element of a tuple.

Was it helpful?

Solution 2

If you only know the first part of the key, you can find out if any of the keys contain it:

if any(k[0] == 1 for k in x):

Or, to get a list of matching keys:

keys = [k for k in x if k[0] == 1]

OTHER TIPS

You need to test for the full key:

(1, 'test') in x

Tuple keys are not special and using a tuple as a key does not mean that both elements in the tuple become separate keys.

If you need both 1 and 'test' to be keys, you need to add those separately as keys, or test every key in the dictionary separately.

You could subclass the dict type and extend it to support your interpretation:

class tupledict(dict):
    def __contains__(self, key):
        if super(tupledict, self).__contains__(key):
            return True
        return any(key in k for k in self)

Demo:

>>> x = tupledict({(1, 'test'): ['marry', 'tom']})
>>> 1 in x
True
>>> (1, 'test') in x
True
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top