Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No has_key() method for Python 3 dictionaries

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?

like image 469
Alexander Prokofyev Avatar asked Jun 15 '12 13:06

Alexander Prokofyev


People also ask

How do you check if a key exists in a dictionary Python3?

Checking if key exists using the get() method The get() method is a dictionary method that returns the value of the associated key. If the key is not present it returns either a default value (if passed) or it returns None. Using this method we can pass a key and check if a key exists in the python dictionary.

How do you remove a key from a dictionary?

Because key-value pairs in dictionaries are objects, you can delete them using the “del” keyword. The “del” keyword is used to delete a key that does exist. It raises a KeyError if a key is not present in a dictionary.

Does Iteritems have no attribute?

Conclusion # The Python "AttributeError: 'dict' object has no attribute 'iteritems'" occurs because the iteritems() method has been removed in Python 3. To solve the error, use the items() method, e.g. my_dict. items() , to get a view of the dictionary's items.

Can you hash a dictionary in Python?

On the other hand, the main use cases of the Python hash function is to compare dictionary keys during a lookup. Anything that is hashable can be used as a key in a dictionary, for example {(1,2): "hi there"} . This situation sets us up for a simple MD5 based hashing of dictionaries.


1 Answers

Python 3 has dictionary key views 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 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:

[key for key in some_dict if key in another_dict]

An even closer match of original code would be to use dict.__contains__(), which is the magic method corresponding to the in operator:

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

But please, don't use this code. I recommend going with the first version, which is the only one highlighting the symmetry between some_dict and another_dict.

like image 178
Sven Marnach Avatar answered Oct 27 '22 00:10

Sven Marnach