Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use 'has_key()' or 'in' on Python dicts?

I wonder what is better to do:

d = {'a': 1, 'b': 2} 'a' in d True 

or:

d = {'a': 1, 'b': 2} d.has_key('a') True 
like image 365
igorgue Avatar asked Aug 24 '09 16:08

igorgue


People also ask

Should I use dict () or {}?

With CPython 2.7, using dict() to create dictionaries takes up to 6 times longer and involves more memory allocation operations than the literal syntax. Use {} to create dictionaries, especially if you are pre-populating them, unless the literal syntax does not work for your case.

Are sets faster than Dicts Python?

Basis of Dictionaries and Sets Compared with lists and tuples, the performance of dictionaries is better, especially for search, add, and delete operations. A dictionary can be completed within a constant time complexity.

Are Python Dicts ordered by default?

Are dictionaries ordered in Python 3.6+? They are insertion ordered. As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted.

When should a dictionary be used in Python?

Python dictionaries can be used when the data has a unique reference that can be associated with the value. As dictionaries are mutable, it is not a good idea to use dictionaries to store data that shouldn't be modified in the first place.


2 Answers

in is definitely more pythonic.

In fact has_key() was removed in Python 3.x.

like image 167
tonfa Avatar answered Oct 13 '22 23:10

tonfa


in wins hands-down, not just in elegance (and not being deprecated;-) but also in performance, e.g.:

$ python -mtimeit -s'd=dict.fromkeys(range(99))' '12 in d' 10000000 loops, best of 3: 0.0983 usec per loop $ python -mtimeit -s'd=dict.fromkeys(range(99))' 'd.has_key(12)' 1000000 loops, best of 3: 0.21 usec per loop 

While the following observation is not always true, you'll notice that usually, in Python, the faster solution is more elegant and Pythonic; that's why -mtimeit is SO helpful -- it's not just about saving a hundred nanoseconds here and there!-)

like image 25
Alex Martelli Avatar answered Oct 14 '22 01:10

Alex Martelli