The implementation of OrderedDict.__delitem__ in Python 3.7 is as follows:

def __delitem__(self, key, dict_delitem=dict.__delitem__):
    'od.__delitem__(y) <==> del od[y]'
    # Deleting an existing item uses self.__map to find the link which gets
    # removed by updating the links in the predecessor and successor nodes.
    dict_delitem(self, key)
    link = self.__map.pop(key)
    link_prev = link.prev
    link_next = link.next
    link_prev.next = link_next
    link_next.prev = link_prev
    link.prev = None
    link.next = None

This code does 3 things:

  • Remove an item from the internal key-value dictionary.
  • Remove a node from the dictionary holding linked list nodes.
  • Delete an item from a doubly linked list.

Since the average case complexity of all the above operations is constant, the average case complexity of OrderedDict.__delitem__ is constant as well.

Do note however that the worst case complexity of deleting a key from a dictionary is O(n), so the same applies for ordered dictionaries as well.

Answer from Agost Biro on Stack Overflow
Discussions

dictionary - how is the time complexity of dict.clear() is O(1) in python? - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Ask questions, find answers and collaborate at work with Stack Overflow for Teams More on stackoverflow.com
🌐 stackoverflow.com
python - Removing key/value pairs in list of dicts - Code Review Stack Exchange
I have a list of dicts that all have the same keys. If a key's value is None in all dicts then I want to remove them (A solution that creates a new dict is fine as well). I'm concerned about my B... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
September 7, 2017
How can I remove a key from a Python dictionary? - Stack Overflow
I want to remove a key from a dictionary if it is present. I currently use this code: if key in my_dict: del my_dict[key] Without the if statement, the code will raise KeyError if the key is not More on stackoverflow.com
🌐 stackoverflow.com
How to get any element in a dictionary without a key, O(1) time complexity - Page 3 - Scripting Support - Developer Forum | Roblox
I’d like to get any element in the dictionary without a key, O(1) time complexity. Example dictionary local dictionary = { Key1 = "Stop", Key2 = "Woke", Key3 = "Developers" } Is there a way to get any value, whe… More on devforum.roblox.com
🌐 devforum.roblox.com
April 23, 2024
🌐
GeeksforGeeks
geeksforgeeks.org › python › time-complexities-of-python-dictionary
Time Complexities of Python Dictionary - GeeksforGeeks
July 23, 2025 - Copying a dictionary creates a shallow copy and its time complexity is O(n) as each key-value pair is duplicated. ... The clear() method removes all elements from the dictionary with a time complexity of O(1).
🌐
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....
🌐
Medium
binarybeats.medium.com › python-dictionary-understanding-methods-with-examples-aa367ede8650
Python Dictionary: Understanding Methods with Examples | by Binary Beats | Medium
April 24, 2023 - The time complexity of these methods is O(n), where n is the number of key-value pairs in the dictionary, as they need to iterate over all the items in the dictionary. The pop() method removes and returns the value associated with the specified key.
🌐
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...
🌐
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)....
Find elsewhere
🌐
Bomberbot
bomberbot.com › python › how-to-remove-a-key-from-a-python-dictionary-delete-keys-from-dicts
How to Remove a Key from a Python Dictionary – Delete Keys from Dicts - Bomberbot
In this situation, the other colliding keys must be reinserted into the dictionary‘s underlying hash table, taking O(n) time. Thankfully, Python‘s dictionary implementation is highly optimized to avoid collisions and the worst case behavior is rare. But it‘s still important to be aware ...
🌐
DataCamp
datacamp.com › tutorial › python-pop
How to Use the Python pop() Method | DataCamp
July 31, 2024 - When we use the pop() method to remove the first or any other element, it works in O(n) time because it involves removing an element and shifting the other elements to a new index order. Check out our Analyzing Complexity of Code through Python tutorial to learn more about time complexity in Python.
🌐
Python
wiki.python.org › moin › TimeComplexity
TimeComplexity - Python Wiki
Both ends are accessible, but even looking at the middle is slow, and adding to or removing from the middle is slower still. See dict -- the implementation is intentionally very similar. As seen in the source code the complexities for set difference s-t or s.difference(t) (set_difference()) and in-place set difference s.difference_update(t) (set_difference_update_internal()) are different!
🌐
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]
🌐
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 - A: For deleting by key, del and pop() are both efficient (O(1) average time complexity). If you need to filter many items, creating a new dictionary with comprehension might be clearer and safer than repeated in-place deletions.
🌐
Python Morsels
pythonmorsels.com › time-complexities
Python Big O: the time complexities of different data structures in Python - Python Morsels
April 16, 2024 - Thanks to the power of hashing, ... the value of an item, and removing an item are all constant time operations (that's O(1) in big O)....
🌐
GeeksforGeeks
geeksforgeeks.org › python-ways-to-remove-a-key-from-dictionary
Python - Ways to remove a key from dictionary - GeeksforGeeks
January 30, 2025 - For example a = [("name", "Ak"), ("age", 25), ("city", "NYC")] is a list we need to convert it to dictionary so that output should be a flat dictionary {'name': 'Ak', 'age': 3 min read Python - Insertion at the beginning in OrderedDict
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.

Top answer
1 of 1
6

Any solution will have to read the values associated to each key of each dictionary; so you won't be able to drop under \$\mathcal{O}(n\times{}m)\$ where \$m\$ is the length of each dictionary. This is pretty much what you are doing, but the if k not in keep_keys call slows things a bit as it is \$\mathcal{O}(m)\$ when it could be \$\mathcal{O}(1)\$ by using a set or a dictionary.

If you change the keep_keys list into a set you simplify the logic a bit: as soon as you find a key whose value is not None you can add it into the set.

dicts = [{'a': 1, 'b': None, 'c': 4}, {'a': 2, 'b': None, 'c': 3}, {'a': None, 'b': None, 'c': 3}]
expected = [{'a': 1, 'c': 4}, {'a': 2, 'c': 3}, {'a': None, 'c': 3}]

keep_keys = set()

for d in dicts:
    for key, value in d.items():
        if value is not None:
            keep_keys.add(key)

remove_keys = set(d) - keep_keys

for d in dicts:
    for k in remove_keys:
        del d[k]

print dicts == expected

This code, as your original one, assume that there is at least one item in dicts; otherwise set(d) will generate an exception as the variable d is not defined yet.


But this code mixes the actual logic with some tests. You should wrap it in a function to ease reusability and put the testing code under an if __name__ == '__main__': clause:

def filter_nones(dictionaries):
    if not dictionaries:
        return

    keep_keys = set()

    for dict_ in dictionaries:
        for key, value in dict_.iteritems():
            if value is not None:
                keep_keys.add(key)

    remove_keys = set(dict_) - keep_keys

    for dict_ in dictionaries:
        for key in remove_keys:
            del dict_[key]


if __name__ == '__main__':
    dicts = [
            {'a': 1, 'b': None, 'c': 4},
            {'a': 2, 'b': None, 'c': 3},
            {'a': None, 'b': None, 'c': 3},
    ]
    expected = [
            {'a': 1, 'c': 4},
            {'a': 2, 'c': 3},
            {'a': None, 'c': 3},
    ]

    filter_nones(dicts)
    print dicts == expected
🌐
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 ...
🌐
Roblox Developer Forum
devforum.roblox.com › help and feedback › scripting support
How to get any element in a dictionary without a key, O(1) time complexity - Page 3 - Scripting Support - Developer Forum | Roblox
April 23, 2024 - I’d like to get any element in the dictionary without a key, O(1) time complexity. Example dictionary local dictionary = { Key1 = "Stop", Key2 = "Woke", Key3 = "Developers" } Is there a way to get any value, whe…