Python dictionary delete all keys

Remove Multiple keys from Python Dictionary

How to remove multiple keys from Python Dictionary? To remove multiple keys you have to create a list or set with the keys you want to delete from a dictionary and iterate it and use either the del keyword or the pop() function to delete each key from the list.

In this article, I will explain the del keyword, pop() function, dictionary comprehension, and for loop to remove the specified multiple keys from the dictionary with examples.

1. Quick Examples of Remove Multiple Keys from Dictionary

Following are quick examples of removing multiple keys from the Dictionary.

 # Below are the quick examples # Example 1: Remove multiple keys using del keyword keys_list = ['fee', 'discount', 'course'] for key in keys_list: del my_dictPython dictionary delete all keys # Example 2: Use pop() & list comprehension to # remove multiple keys from dictionary keys_list = ['fee', 'discount', 'course'] [my_dict.pop(key) for key in keys_list] # Example 3: Remove multiple keys from dictionary my_dict = # Example 4: Using items()along with list comprehension & dict() # Remove multiple keys from dictionary my_dict = dict([(key, val) for key, val in my_dict.items() if key not in keys_list]) # Example 5: Remove multiple keys using for loop print("Before removing the key:\n", my_dict) keys_list = ["course", "duration"] for key in keys_list: del my_dictPython dictionary delete all keys # Example 6: Remove all keys using clear() my_dict = # empty the dictionary my_dict.clear() print("Length", len(my_dict)) # Example 7: Remove all keys using del my_dict =

2. What is Python Dictionary

A Python dictionary is a collection that is unordered, mutable, and does not allow duplicates. Each element in the dictionary is in the form of key:value pairs. Dictionary elements should be enclosed with <> and key: value pair separated by commas. The dictionaries are indexed by keys.

Читайте также:  Mcc tool chest java to bedrock

Moreover, dictionaries are mutable data types, which means that you can be added, deleted, and updated their key:value pairs. keys are an immutable type such as string, numbers(int, float), and tuple. In case, you add duplicates, it will update the existing key with the new value.

Let’s create a Python dictionary,

 # Create dictionary my_dict = print(my_dict) 

Remove multiple keys from Python dictionary

3. Remove Multiple Keys from Dictionary

We can use a del keyword and for loop to remove the multiple keys from the dictionary in Python. First, we have to initialize the list of keys that we want to remove from the dictionary. Then using the del keyword we will remove the list of specified keys from the dictionary with the help of iterating. Here is an example. After removing the specified multiple key, I printed the remaining key-value pairs from the dictionary to the console.

 # Create removed keys list keys_list = ['fee', 'discount', 'course'] print("Before removing the multiple keys: \n", my_dict) # Remove multiple keys using del keyword and for loop for key in keys_list: del my_dictPython dictionary delete all keys # Print print("After removing the multiple keys: \n", my_dict) 

Yields below output. Note that removing a key actually removes the key and the value associated with it.

Remove multiple keys from Python dictionary

4. Remove Multiple Keys from Dictionary using pop()

The python dictionary pop() function is another method that can be used to remove the keys from the dictionary, this returns the value related to the removed key . If a key does not exist in the dictionary and the default value is specified, then returns the default value; else throws a KeyError .

Note that using the pop() function we can remove the single key at a time, but with the help of list comprehension you can delete multiple keys. Here, list comprehension iterates a list of specified multiple keys and removes them from the dictionary.

Let’s pop the specified key with help of list comprehension to remove list of multiple keys from the Python dictionary.

 # Use pop() & list comprehension to # remove multiple keys from dictionary # Create removed keys list keys_list = ['fee', 'discount', 'course'] [my_dict.pop(key) for key in keys_list] print("After removing the multiple keys: \n", my_dict) 

Remove multiple keys from Python dictionary

5. Remove Multiple keys using Dictionary Comprehension

Alternatively, we can use dictionary comprehension along with the if condition and not in operator we can remove specified multiple keys from the dictionary and return a new dictionary that contains the remaining key-value pairs of the dictionary.

 # Remove multiple keys from dictionary my_dict = print("After removing the multiple keys: \n", my_dict) # Output: # After removing the multiple keys: #

6. Remove Multiple keys from Dictionary using items()

Using Python item() function along with dict() function and list comprehension we can also remove multiple keys from the dictionary. In this example, we create a new dictionary using dict() function instead of removal keys and using items() function we can extract key-value pairs and iterate them using list comprehension.

 # Using items()along with list comprehension & dict() # Remove multiple keys from dictionary my_dict = dict([(key, val) for key, val in my_dict.items() if key not in keys_list]) print("After removing the multiple keys: \n", my_dict) # Output: # After removing the multiple keys: #

7. Remove Multiple Keys using For Loop

We can also delete multiple keys by looping through the dictionary using for loop. It will iterate the list of specified multiple keys from the dictionary and then remove them using the del keyword.

 # Remove multiple keys using for loop print("Before removing the key:\n", my_dict) keys_list = ["course", "duration"] for key in keys_list: del my_dictPython dictionary delete all keys print("After removing the keys:\n", my_dict) # Output: # Before removing the key: # # After removing the keys: #

8. Remove All Keys using del

Using del keyword we can remove all key-value pairs from a dictionary.

 # Remove all keys using del my_dict = # empty the dictionary del my_dict 

9. Delete all Keys from Dictionary using clear()

The Python dictionary clear() function is used to remove all key-value pairs from the dictionary. The clear() function doesn’t return any value.

 # Remove all keys using clear() my_dict = # empty the dictionary my_dict.clear() print("Length", len(my_dict)) print(my_dict) # Output: # Length 0 # <> 

10. Conclusion

In this article, I have explained the Python del keyword, pop() function, dict comprehension, and for loop to remove the specified multiple keys from Python dictionary with examples.

  • Remove duplicates from Python list
  • Python remove from list by index
  • Python remove set element if exists
  • How to Remove a Key from Python Dictionary?
  • Python get dictionary keys as a list
  • Get all keys from dictionary in Python
  • Python sort dictionary by key
  • How to sort dictionary by value in Python
  • How to create nested dictionary in Python
  • Python check if key exists in dictionary
  • Python iterate over a dictionary
  • Python add keys to dictionary
  • How to append Python dictionary to dictionary?
  • How to convert Python dictionary to JSON?
  • How to add items to a Python dictionary?
  • Sort Python dictionary explained with examples
  • Python dictionary comprehension
  • Dictionary methods
  • Python get dictionary values as list

References

You may also like reading:

Источник

Python Remove Key from Dictionary – How to Delete Keys from a Dict

Shittu Olumide

Shittu Olumide

Python Remove Key from Dictionary – How to Delete Keys from a Dict

Dictionaries are a useful data type in Python for storing data in a key-value format. And there are times when you might need to remove a particular key-value pair from a dictionary.

You’ll learn some dictionary basics, as well as how to delete keys, in this tutorial.

How to Write a Dict in Python

Dictionaries are denoted by curly braces <> and the key-value pairs are separated by colons : . For example, the following code initializes a dictionary with three key-value pairs:

You can also initialize dictionaries using the built-in dict() function. For example:

my_dict = dict(apple=2, banana=3, orange=5) 

Now I’ll teach you how to securely remove keys from a Python dictionary. When I say «securely,» I mean that if the key doesn’t actually exist in the dictionary, the code won’t throw an error.

We’ll discover how to accomplish this using the del keyword, the pop() method, and the popitem() method. Finally, you’ll see how to use Python to remove multiple keys from a dictionary.

How to Remove a Key from a Dict Using the del Keyword

The most popular method for removing a key:value pair from a dictionary is to use the del keyword. You can also use it to eliminate a whole dictionary or specific words.

Simply use the syntax shown below to access the value you need to delete:

Let’s have a look at an example:

Members = del Members["Doe"] print(Members) 

How to Remove a Key from a Dict Using the pop() Method

Another technique to remove a key-value pair from a dictionary is to use the pop() method. The syntax is shown below:

dictionary.pop(key, default_value) 
My_Dict = data = My_Dict.pop(1) print(data) print(My_Dict) 

How to Remove a Key from a Dict Using the popitem() Function

The built-in popitem() function eliminates the the last key:value pair from a dictionary. The element that needs to be removed cannot be specified and the function doesn’t accept any inputs.

The syntax looks like this:

Let’s consider and example for a better understanding.

# initialize a dictionary My_dict = # using popitem() Deleted_key = My_dict.popitem() print(Deleted_key) 

As you can see, the function removed the last key:value pair – 5: «Black» – from the dictionary.

How to Remove Multiple Keys from a Dict

You can easily delete multiple keys from a dictionary using Python. The .pop() method, used in a loop over a list of keys, is the safest approach for doing this.

Let’s examine how we can supply a list of unique keys to remove, including some that aren’t present:

My_dict = #define the keys to remove keys = ['Sam', 'John', 'Doe'] for key in keys: My_dict.pop(key, None) print(My_dict) 

One thing to note is that in the pop() method inside the loop, we pass in None and the default value, just to make sure no KeyError is printed if a key doesn’t exist.

How to Remove All Keys from a Dict Using the clear() Method

You can use the clear() method to remove all key-value pairs from a dictionary. The syntax is as follows:

Colors = Colors.clear() print(Colors) 

Conclusion

For removing a key-value pair or several key-value pairs from a dictionary, we discussed a variety of Python methods in this article.

You can do so using the del keyword, which is the most common method of removing a key-value pair from a dictionary. The pop() method is useful when we need to remove a key-value pair and also get the value of the key-value pair. Using the popitem() function, we can remove the final key-value pair in a dictionary.

Also, if you need to remove all key:value pairs in a dictionary, you can use the clear() method.

Let’s connect on Twitter and on LinkedIn. You can also subscribe to my YouTube channel.

Источник

Оцените статью