Last Updated on May 28, 2024 by Roshan Parihar
To delete multiple keys items from Dictionary in Python, use the pop()
function and pass the key as an argument to remove with its value.
You can also delete all items in Dictionary by using the Python clear()
function.Let’s find out with the examples given below.
Delete Multiple Keys Items of Dictionary Using pop() in Python
If you want to delete multiple keys items of Dictionary, you have to use the pop()
function in Python. It just require to pass a keys as an argument to delete with its value. Use array of keys with for loop to iterate through each elements and delete multiple items.
Examples 1
1 2 3 4 5 |
myDict = {'one': 'Sally', 'two': 13, 'three': 'Dingra', 'four': 'Lilop'}; myElementDel = ('one', 'three', 'four'); for d in myElementDel: myDict.pop(d); print(myDict); |
Output
The above example first stores the keys in an array. After that, it uses the for loop iterate through each elements and use pop()
function to delete one-by-one. As a result, there is only one element remain after the deletion which is with the key ‘two’. The example delete list of keys from dictionary which are ‘one’, ‘three’, and ‘four’.
Remove Single Item From Dictionary Using Python pop()
To remove the single item from Dictionary in Python, you have to use the pop()
function of Python without loop. In the function, you have to pass the single key which you want to remove.
If the key is a string, enclose it within the quotes(‘). While, if the integer is key to delete, you have to just pass it without any quotes.
Examples 2
1 2 3 |
myDict = {'one': 'Sally', 'two': 13, 'three': 'Dingra', 'four': 'Lilop'}; myDict.pop('two'); print(myDict); |
Output
The above example contains 4 elements before the code execution. After the execution of the code, the Dictionary showing only the 3 elements.
Because the key is a string, you have to pass it as an argument and within single quotes(‘). Hence, the output gives the elements without the element with the key ‘two’.
Eliminate All Elements Using Clear() Function
Likewise, the above all examples, you can also remove all element of Dictionary using clear()
function. The clear()
function requires no argument to remove all the elements.
Examples 3
1 2 3 |
myDict = {'one': 'Sally', 'two': 13, 'three': 'Dingra', 'four': 'Lilop'}; myDict.clear(); print(myDict); |
Output
Finally, the above output shows that there are no elements in myDict. You may see only the curly({}) brackets in the output.
DOWNLOAD Free PYTHON CHEAT SHEET
You May Also Like to Read