There is no has_key () method for Python 3 dictionaries

I read the Python Cookbook and see that the recipe for Finding the Cross of Two Dictionaries recommends using this single-line font:

filter(another_dict.has_key, some_dict.keys())

But since Python 3 dictionaries do not have a has_key () method, how do I modify the suggested code? I suppose there might be some kind of internal __ in the __ () method or something like that.

Any ideas please?

+5
source share
1 answer

Python 3 has vocabulary keywords instead, a much more powerful concept. Your code can be written as

some_dict.keys() & another_dict.keys()

in Python 3.x. This returns the shared keys of the two dictionaries as a set.

It is also available in Python 2.7 using the method dict.viewkeys().

:

[key for key in some_dict if key in another_dict]

dict.__contains__(), , in:

filter(another_dict.__contains__, some_dict.keys())

, , . , , some_dict another_dict.

+17

All Articles