Today a very brief topic about using has_key and my journey on finding that it does not work on Python3. Check out!

S0-E26/E30 :)

Python Dictionaries

Let's say you have a dict like this:

test_dict = {"testkey": "testvalue", "TestKey2": "TEstkeyVal2"}

And you want to know that there is a testkey in this dictionary.

At python2+ you could do that :

test_dict = {"testkey": "testvalue", "TestKey2": "TEstkeyVal2"}
assert test_dict.has_key("testkey")

And the assertion would not raise.

But in Python3+ you have an error:

assert test_dict.has_key("testkey")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  AttributeError: 'dict' object has no attribute 'has_key'

That's because has_key has been removed from python3.

What should I do?

Instead of using has_key use in.

assert "testkey" in test_dict

Should I use dict.keys() to check then?

Short version - you should not - why ? because you may find yourself someday in a performance issue that is hard to trace.

So don't make use of something like this:

if "key1" in dict1.keys()

Instead use:

if "key1" in dict1

Check this stackoverflow comment about performance

or in this hidden code that I've copy-pasted so you don't need to go to SO:

Acknowledgements

Thanks!

That's it :) Comment, share or don't :)

If you have any suggestions what I should blog about in the next articles - please give me a hint :)

See you tomorrow! Cheers!



Comments

comments powered by Disqus