Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the complexity of calling of dict.keys() in Python 3?

What's the asymptotic complexity of dict.keys() in python?

I found this website but it does not have the answer. I am using Python 3, but I guess this is not version specific.

like image 531
Filip Haglund Avatar asked Aug 24 '15 12:08

Filip Haglund


People also ask

What is the time complexity for dict keys ()?

It's complexity is 0(1) in Python 3. x. In Python 2. x, it returns a list so populating it or performing some lookup on it takes 0(n) .

What is time complexity of dict in Python?

Lookups are faster in dictionaries because Python implements them using hash tables. If we explain the difference by Big O concepts, dictionaries have constant time complexity, O(1) while lists have linear time complexity, O(n).

What does dict keys () do in Python?

The methods dict. keys() and dict. values() return lists of the keys or values explicitly. There's also an items() which returns a list of (key, value) tuples, which is the most efficient way to examine all the key value data in the dictionary.

Does Python have key complexity?

Short answer: worst case it is O(n). But the average case time complexity is O(1).


1 Answers

In Python 3, dict.keys() returns a view object. Essentially, this is just a window directly onto the dictionary's keys. There is no looping over the hashtable to build a new object, for example. This makes calling it a constant-time, that is O(1), operation.

View objects for dictionaries are implemented starting here; the creation of new view objects uses dictview_new. All that this function does is create the new object that points back at the dictionary and increase reference counts (for garbage tracking).

In Python 2, dict.keys() returns a list object. To create this new list, Python must loop over the hashtable, putting the dictionary's keys into the list. This is implemented as the function dict_keys. The time complexity here is linear with the size of the dictionary, that is O(n), since every slot in the table must be visited.

N.B. dict.viewkeys() in Python 2 does the same as dict.keys() in Python 3.

like image 145
Alex Riley Avatar answered Nov 02 '22 23:11

Alex Riley