How to Delete Multiple Keys Items From Dictionary In Python

Last Updated on May 25, 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

Output

{‘two’: 13}

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

Output

{‘one’: ‘Sally’, ‘three’: ‘Dingra’, ‘four’: ‘Lilop’}

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’.

Bonus: download a Free Python cheat sheet that will show you 20+ most important examples to learn in Python.

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

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