What is the time complexity of dict.keys() in Python?
<p>I came across a question when I solve <a href="https://leetcode.com/problems/insert-delete-getrandom-o1/">this LeetCode problem</a>. Although my solution got accepted by the system, I still do not have any idea after searching online for the following question:
<code>What is the time complexity of dict.keys() operation?</code> Does it return a view of the keys or a real list (stores in memory) of the keys?</p>

<p>In Python 2, it's O(n), and it builds a new list. In Python 3, it's O(1), but it doesn't return a list. To draw a random element from a dict's <code>keys</code>, you'd need to convert it to a list.</p>

<p>It sounds like you were probably using <code>random.choice(d.keys())</code> for part 3 of that problem. If so, that was O(n), and you got it wrong. You need to either implement your own hash table or maintain a separate list of elements, without sacrificing average-case O(1) insertions and deletions.</p>

python