Fixed time (O(1)). If you need the exact value on your computer, run a benchmark. Answer from This_Growth2898 on reddit.com
Discussions

dictionary - how is the time complexity of dict.clear() is O(1) in python? - Stack Overflow
But this is purely a function of the GC approach that CPython uses (i.e. reference counting); you can envision different approaches that wouldn't require explicit cleanup like this, or where the cleanup would happen much later (or even be amortized away). Since ideally the time complexity of ... More on stackoverflow.com
🌐 stackoverflow.com
How to delete from a deque in constant time without "pointers"?

There's a technique which I call 'lazy popping' which can help here.

The idea is that you don't delete immediately from the queue. Rather, you leave deleted items in the queue, but mark them as deleted in another data structure -- usually a set. Whenever you have to pop an item to execute, keep popping until you reach an item that hasn't yet been deleted.

This gives you constant-time push, amortized constant-time pop (although you may pop multiple deleted items off the queue each time you pop an item to execute, each item only gets popped exactly once) , and constant-time deletion, which is better than what you can get by maintaining a list and deleting from start or middle.

In this case, you'd save the IDs of deleted items in the set. It looks like this (untested code):

import collections

class DeletableQueue:
    def __init__(self):
        self.deleted = set()
        self.queue = collections.deque()
    def push(self, item):
        self.queue.append(item)
    def pop(self):
        # Precondition: there is at least one non-deleted item on the queue.
        while id(q[0]) in deleted:
            q[0].pop_left()  # Discard an already-deleted item.
        return q.pop_left()  # Return the actual item to pop
    def delete(self, item_to_delete):
        self.deleted.add(id(item_to_delete))
More on reddit.com
🌐 r/learnpython
15
6
October 20, 2014
how much time will it take to remove a key, value pair from a dictionary?
Fixed time (O(1)). If you need the exact value on your computer, run a benchmark. More on reddit.com
🌐 r/learnpython
9
6
June 23, 2023
Time complexity of Counters in Python
And if so, wouldn't the time complexity of checking if a key is in a dictionary be O(n) Your link says O(1) on average, assuming a good enough hash function. More on reddit.com
🌐 r/learnpython
10
5
February 21, 2022
🌐
GeeksforGeeks
geeksforgeeks.org › python › time-complexities-of-python-dictionary
Time Complexities of Python Dictionary - GeeksforGeeks
July 23, 2025 - The 'in' keyword allows us to check if a key exists in the dictionary with an average complexity of O(1). ... Iterating over keys, values, or items in a dictionary has a time complexity of O(n) where n is the number of elements.
🌐
Python
wiki.python.org › moin › TimeComplexity
TimeComplexity - Python Wiki
[3] = For these operations, the worst case n is the maximum size the container ever achieved, rather than just the current size. For example, if N objects are added to a dictionary, then N-1 are deleted, the dictionary will still be sized for N objects (at least) until another insertion is made.
🌐
Pythontutor
pythontutor.net › home › python tutorial › python dictionaries › dictionary time complexity
Python Dictionary Time Complexity – Operations Explained with Examples
Deleting a dictionary entry also runs in constant time in most cases. ... Python quickly determines whether a key exists using hashing. Iterating through a dictionary requires visiting every element, so the time complexity grows linearly with the size of the dictionary.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-delete-items-from-dictionary-while-iterating
Python | Delete items from dictionary while iterating - GeeksforGeeks
July 11, 2025 - Python3 · # Creating a dictionary ... print(myDict) Output · {1: 'Geeks', 3: 'Geeks'} Time complexity: O(1) for removing the key-value pair using pop() method....
🌐
Pythondictionary
pythondictionary.org › home › dictionary performance
Dictionary Performance and Time Complexity | PythonDictionary.org | PythonDictionary.org
April 20, 2025 - This page explores the performance characteristics of Python dictionaries, including time complexity analysis, internal implementation details, and optimization techniques. Python dictionaries are implemented using hash tables, which provide fast lookup, insertion, and deletion operations.
🌐
JOOS
joosjuliet.github.io › complexity_of_python_operations
python operations time complexity – JOOS
Reading time ~2 minutes · python sort 알고리즘은 Timsort이다. 참고자료 : [https://medium.com/@fiv3star/python-sorted-알고리즘-timsort-dca0ec7a08be] … dict 만세 · set 만세…
Find elsewhere
🌐
Pythondictionary
pythondictionary.org › home › dictionary methods
Python Dictionary Methods Reference | PythonDictionary.org | PythonDictionary.org
April 25, 2025 - # Remove all items from the dictionary ... to list if needed keys_list = list(person.keys()) # Result: ['name', 'age'] Time Complexity: O(1) for creating view, O(n) for conversion...
🌐
Abdullahslab
abdullahslab.com › 2023 › 12 › 05 › python-ordered-dict-constant-time-complexity.html
How does python’s ordered dict have constant time complexity for add, search, and delete?
December 5, 2023 - So, folks, there ya have it! A key-value data structure that maintains the order of insertion, and has constant time add, search, and delete operations! Pretty neat! Python dicts use an additional data structure, a doubly linked list, to maintain insertion order.
🌐
Quora
quora.com › What-is-the-time-complexity-of-checking-if-a-key-is-in-a-dictionary-in-Python
What is the time complexity of checking if a key is in a dictionary in Python? - Quora
This is the reason why python is 10 times slower than cpp. ... The memory used by the algorithm. We mainly focus on time complexity while writing the code. ... To check for a value in a dictionary, rather than a key, you have to do the same thing as with, e.g., a list—iterate the whole thing and check each value for a match.
🌐
UCI
ics.uci.edu › ~pattis › ICS-33 › lectures › complexitypython.txt
Complexity of Python Operations
Dictionaries: dict and defaultdict ... Iteration | for k in d: | O(N) | all forms: keys, values, items | Worst: no return/break in loop So, most dict operations are O(1)....
Top answer
1 of 2
5

Some rationale for why it is being claimed to be O(1):

The clear() method is actually just assigning the internal dictionary structures to new empty values (as can be seen in the source). The seemingly O(n) part is a result of decrementing reference counts, and other GC-related stuff. But this is purely a function of the GC approach that CPython uses (i.e. reference counting); you can envision different approaches that wouldn't require explicit cleanup like this, or where the cleanup would happen much later (or even be amortized away). Since ideally the time complexity of clear() shouldn't depend on the underlying GC approach, all GC-related parts are omitted, making it "O(1)". IMO this is mostly a definitional argument than anything else, but this is at least some justification.

2 of 2
3

I first thought that dict.clear just performed some reference decrease to let the garbage collector do the dirty non-O(1) work, but looking at the source code (thanks timgeb for providing the link) it doesn't seem to be that:

   oldvalues = mp->ma_values;
    if (oldvalues == empty_values)
        return;
    /* Empty the dict... */
    dictkeys_incref(Py_EMPTY_KEYS);
    mp->ma_keys = Py_EMPTY_KEYS;
    mp->ma_values = empty_values;
    mp->ma_used = 0;
    mp->ma_version_tag = DICT_NEXT_VERSION();
    /* ...then clear the keys and values */
    if (oldvalues != NULL) {
        n = oldkeys->dk_nentries;
        for (i = 0; i < n; i++)
            Py_CLEAR(oldvalues[i]);

What I see is that if the dictionary had values, then a loop is performed to decrease references those values and set the pointers to NULL. So seems to be O(n) not O(1) since it depends on the number of the values.

When you assign to a new dict like this d = {}, this is O(1), but the garbage collector must delete the old object when not referenced anymore. That may not be right when assigning, but that will happen, unless python quits abruptly.

🌐
CSDN
devpress.csdn.net › python › 62fdb4e8c677032930804466.html
Complexity of deleting a key from python ordered dict_python_Mangs-Python
August 18, 2022 - Answer a question Deleting a key from a python dict or defaultdict in python is O(1) operation, as mentioned here and here. To remove a key from OrderedDict, we can either use del d[key] or use popite Mangs Python
🌐
Runestone Academy
runestone.academy › ns › books › published › pythonds3 › AlgorithmAnalysis › Dictionaries.html
2.7. Dictionaries — Problem Solving with Algorithms and Data Structures 3rd edition
Figure 4: Comparing the in Operator for Python Lists and Dictionaries¶ · Since Python is an evolving language, there are always changes going on behind the scenes. The latest information on the performance of Python data structures can be found on the Python website. As of this writing the Python wiki has a nice time complexity page that can be found at the Time Complexity Wiki.
🌐
DZone
dzone.com › data engineering › data › python memo 2: dictionary vs. set
Python Memo 2: Dictionary vs. Set
April 15, 2021 - Therefore, on average, this can still ensure that the time complexity of insert, find, and delete is O(1). In this lesson, we have learned the basic operations of dictionaries and sets together, and have explained their high performance and internal storage structure. The dictionary is an ordered data structure in Python 3.7+, while the set is unordered.
🌐
GeeksforGeeks
geeksforgeeks.org › complexity-cheat-sheet-for-python-operations
Complexity Cheat Sheet for Python Operations - GeeksforGeeks
December 13, 2024 - Strings are immutable and behave similarly to tuples in terms of time complexities: ... Amortized complexity applies to append() because resizing happens occasionally. Insertions and deletions at arbitrary positions require shifting elements. ... Hash collisions in dictionaries and sets can degrade O(1)operations to O(n).
🌐
Wander In Dev
wanderin.dev › python-interview › python-dictionaries
Python Dictionaries – Wander In Dev
October 6, 2024 - You can create a dictionary using ... This method removes all items from dict_1. This method has a constant time complexity of O(1)....
🌐
Verve AI
vervecopilot.com › interview-questions › how-does-understanding-python-delete-from-dict-impact-your-interview-success
How Does Understanding Python Delete From Dict Impact Your Interview Success
August 28, 2025 - Q: What's the most efficient way to python delete from dict for very large dictionaries? A: For deleting by key, del and pop() are both efficient (O(1) average time complexity).
🌐
Medium
binarybeats.medium.com › python-dictionary-understanding-methods-with-examples-aa367ede8650
Python Dictionary: Understanding Methods with Examples | by Binary Beats | Medium
April 24, 2023 - One of the most important data structures in Python is the dictionary. In this article, we will explore what a dictionary is, how it can be used, and some important methods of dictionaries in Python. Additionally, we will discuss the time and space complexity of these methods and provide some coding examples.