I read “Python Cookbook” and see what in a recipe “Finding the Intersection of Two Dictionaries” authors recommend using such one-liner:
filter(another_dict.has_key, some_dict.keys())
But since Python 3 dictionaries don’t have has_key() method how should I modify suggested code? I suppose there could be some internal __ in__() method or something like this.
Any ideas, please?
Python 3 has dictionary key views instead, a much more powerful concept. Your code can be written as
in Python 3.x. This returns the common keys of the two dictionaries as a set.
This is also available in Python 2.7, using the method
dict.viewkeys().As a closer match of the original code, you could also use a list comprehension:
An even closer match of original code would be to use
dict.__contains__(), which is the magic method corresponding to theinoperator:But please, don’t use this code. I recommend going with the first version, which is the only one highlighting the symmetry between
some_dictandanother_dict.