[Solved] Why do keys() and items() methods return different Boolean values for same key? (Python 3.6) [closed]


items() contains tuples, key-value pairs:

>>> spam.items()
dict_items([('name', 'Zophie'), ('age', 7)])

Your key is not such a tuple. It may be contained in one of the tuples, but in does not test for containment recursively.

Either test for the correct key-value tuple:

>>> ('name', 'Zophie') in spam.items()
True

or if you can’t get access to just the keys() dictionary view, use the any() function to test each pair individually (iteration is halted early when a match is found):

>>> any('name' in pair for pair in spam.items())
True

or

>>> any(key == 'name' for key, value in spam.items())
True

On a separate note, if all you are doing is testing for a key, then just use key in dictionary. There is no need to create a separate dictionary view over the keys for that case; it’s just a waste of Python cycles and memory as containment testing against the dictionary achieves the exact same result.

solved Why do keys() and items() methods return different Boolean values for same key? (Python 3.6) [closed]