- Remove an element from dictionary python based on index
- 4 Answers 4
- Remove an item from a dictionary in Python (clear, pop, popitem, del)
- Remove all items from a dictionary: clear()
- Remove an item by a key and return its value: pop()
- Remove an item and return its key and value: popitem()
- Remove an item by a key from a dictionary: del
- Remove items that satisfy a condition: Dictionary comprehensions
- How to Remove an Element From Dictionary in Python
- Method 1: Using the “del” statement
- Example
- Method 2: Using the “dict.pop()” method
- Example
- Method 3: Using the popitem() method
- Example
- Method 4: Using the clear() method
- Example
- Python — Remove Dictionary Items
- Example
- Example
- Example
- Example
- Example
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
Remove an element from dictionary python based on index
I have tried dictionary.popitem() that removes ‘t’:6, dictionary.pop(key) removes a key from the dictionary, but I have no way of finding the key I want to remove, I only have the index.
Dictionarys are unordered or insertordered depending on what version of python you use. There is no «leftmost» item.
Dictionaries are only ordered in Python 3.7+, in general though, relying on the order is a sign of the wrong data-structure. But you could just iterate over it and break at the «ith» iteration, and you’ll get the correct key. Note, this require O(N) time. Or just list(my_dict)[index]
4 Answers 4
Assuming you’re doing this in Python 3.7 or later, where dict keys are ordered, you can create an iterator from the dict keys and use the next function to obtain the first key, so that you can use the del statement to remove that key:
If you want to remove a key of a different index, you can use itertools.islice to obtain the key at a given index. For example, to delete the second key (of index 1) from d :
from itertools import islice d = del d[next(islice(d, 1, None))] print(d)
@ggupta By calling the list constructor you’re forcing iterations over all keys of the dict, whereas with islice it can short-circuit once the desired index is reached.
you can do this by iterating your dictionary.
1) if you have only one index to delete
dict = i = 0 for key in dict.keys(): if i == 1: #assuming you want to remove the second element from the dictionary key_to_delete = key i = i + 1 if key_to_delete in dict: del dictDelete item dict python print(dict)
2) if you have multiple indexes to delete:
dict = i = 0 index_to_delete = [1,2] #assuming you want to remove the second and the third elements from the dictionary keys_to_delete = [] for key in dict.keys(): if i in index_to_delete: print(key) keys_to_delete.append(key) i = i + 1 for key in keys_to_delete: if key in dict: del dictDelete item dict python print(dict)
Remove an item from a dictionary in Python (clear, pop, popitem, del)
In Python, to remove an item (element) from a dictionary ( dict ), use the clear() , pop() , popitem() methods or the del statement. You can also remove items that satisfy the conditions using the dictionary comprehensions.
See the following article for how to add items to a dictionary.
Remove all items from a dictionary: clear()
The clear() method removes all items from a dictionary, making it empty.
d = 'k1': 1, 'k2': 2, 'k3': 3> d.clear() print(d) # <>
Remove an item by a key and return its value: pop()
By specifying a key to the pop() method, the item is removed and its value is returned.
d = 'k1': 1, 'k2': 2, 'k3': 3> removed_value = d.pop('k1') print(d) # print(removed_value) # 1
By default, specifying a non-existent key raises a KeyError .
d = 'k1': 1, 'k2': 2, 'k3': 3> # removed_value = d.pop('k4') # print(d) # KeyError: 'k4'
If you pass the second argument, its value is returned if the key does not exist. The dictionary remains unchanged.
d = 'k1': 1, 'k2': 2, 'k3': 3> removed_value = d.pop('k4', None) print(d) # print(removed_value) # None
Remove an item and return its key and value: popitem()
The popitem() method removes an item from the dictionary and returns its key and value as a tuple, (key, value) .
Since Python 3.7, the order of elements in the dictionary is preserved. As a result, popitem() removes elements in LIFO (last in, first out) order.
A KeyError is raised for an empty dictionary.
d = 'k1': 1, 'k2': 2> k, v = d.popitem() print(k) print(v) print(d) # k2 # 2 # k, v = d.popitem() print(k) print(v) print(d) # k1 # 1 # <> # k, v = d.popitem() # KeyError: 'popitem(): dictionary is empty'
Remove an item by a key from a dictionary: del
You can also use the del statement to delete an item from a dictionary.
d = 'k1': 1, 'k2': 2, 'k3': 3> del d['k2'] print(d) #
You can specify and remove multiple items.
d = 'k1': 1, 'k2': 2, 'k3': 3> del d['k1'], d['k3'] print(d) #
If a non-existent key is specified, a KeyError is raised.
d = 'k1': 1, 'k2': 2, 'k3': 3> # del d['k4'] # print(d) # KeyError: 'k4'
Remove items that satisfy a condition: Dictionary comprehensions
To remove items that meet certain conditions from a dictionary, use dictionary comprehensions, which are the dictionary equivalent of list comprehensions.
«Removing items that satisfy a condition» is equivalent to «extracting items that do not satisfy the condition».
For example, to remove items with odd values, you can extract items with even values. The same applies to the opposite case.
d = 'apple': 1, 'banana': 10, 'orange': 100> dc = k: v for k, v in d.items() if v % 2 == 0> print(dc) # dc = k: v for k, v in d.items() if v % 2 == 1> print(dc) #
The items() method of dict is used to extract keys and values.
You can also specify conditions based on the keys.
dc = k: v for k, v in d.items() if k.endswith('e')> print(dc) # dc = k: v for k, v in d.items() if not k.endswith('e')> print(dc) #
You can use and and or to specify multiple conditions.
dc = k: v for k, v in d.items() if v % 2 == 0 and k.endswith('e')> print(dc) #
How to Remove an Element From Dictionary in Python
Method 1: Using the “del” statement
To remove an element from a dictionary using the del statement, “specify the key of the element you want to remove after the del keyword”. The element with the specified key will be removed from the dictionary. If the key is not found in the dictionary, a KeyError will be raised.
Example
main_dict = # Remove the element with the key 'B' del main_dict['B'] print(main_dict)
Method 2: Using the “dict.pop()” method
The “dict.pop()” method allows you to remove an element with a specified key and return its value. You must pass the key of the element you want to remove as an argument to the pop() method.
If the key is not found in the dictionary, a KeyError will be raised. However, you can also provide a default value as a second argument to the pop() method, which will be returned instead of raising a KeyError when the key is not found in the dictionary.
Example
main_dict = # Remove the element with the key 'B' main_dict.pop('B') print(main_dict)
The “dict.pop()” method removes the element with the specified key and returns its value. If the key is not found, a KeyError will be raised.
main_dict = # Remove the element with the key 'B' main_dict.pop('D') print(main_dict)
KeyError: 'D'
Method 3: Using the popitem() method
The popitem() method “removes an element from the dictionary and returns its key and value as a tuple, (key, value).”
Example
cars = cars.popitem() print(cars)
Method 4: Using the clear() method
The clear() method removes all elements from a dictionary, making it empty.
Example
cars = cars.clear() print(cars)
Python — Remove Dictionary Items
There are several methods to remove items from a dictionary:
Example
The pop() method removes the item with the specified key name:
Example
The popitem() method removes the last inserted item (in versions before 3.7, a random item is removed instead):
Example
The del keyword removes the item with the specified key name:
Example
The del keyword can also delete the dictionary completely:
thisdict = <
«brand»: «Ford»,
«model»: «Mustang»,
«year»: 1964
>
del thisdict
print(thisdict) #this will cause an error because «thisdict» no longer exists.
Example
The clear() method empties the dictionary:
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.