Python dict drop key

Remove key from Dictionary in Python

In this article we will discuss 6 different ways to delete a key from a dictionary in python.

# Dictionary of strings and int word_freq_dict =

Now we want to remove an item from this dictionary whose key is “at”. There are different ways to do that. Let’s explore them one by one,

Remove a key from a dictionary using dict.pop()

In Python dictionary class provides a method pop() to delete an item from the dictionary based on key i.e.

  • If the given key exists in the dictionary then dict.pop() removes the element with the given key and return its value.
  • If the given key doesn’t exist in the dictionary then it returns the given Default value.
  • If the given key doesn’t exist in the dictionary and No Default value is passed to pop() then it will throw KeyError

Let’s delete an element from dict using pop(),

Frequently Asked:

key_to_be_deleted = 'this' # As 'this' key is present in dict, so pop() will delete # its entry and return its value result = word_freq_dict.pop(key_to_be_deleted, None) print("Deleted item's value = ", result) print("Updated Dictionary :", word_freq_dict)

Deleted item’s value = 43 Updated Dictionary :

It deleted the key-value pair from dictionary where the key was ‘this’ and also returned its value.

Delete a Key from dictionary if exist using pop()

The default value in pop() is necessary, because if the given key is not present in the dictionary and no default value is given in pop() then it will throw keyError. Let’s delete an element that is not present in the dictionary using the pop() function and without passing a default value argument in pop() i.e.

key_to_be_deleted = 'where' word_freq_dict.pop(key_to_be_deleted)

If the given key in pop() function is not present in the dictionary and also default value is not provided, then pop() can throw KeyError. So to avoid that error we should always check if key exist in dictionary before trying to delete that using pop() function and without any default value i.e.

key_to_be_deleted = 'where' if key_to_be_deleted in word_freq_dict: word_freq_dict.pop(key_to_be_deleted) else: print(f'Key is not in the dictionary')
Key where is not in the dictionary

We can also use the try/except to handle that error,

key_to_be_deleted = 'where' try: word_freq_dict.pop(key_to_be_deleted) except KeyError: print(f'Key is not in the dictionary')
Key where is not in the dictionary

Remove a key from a dictionary using items() & for loop

Iterate over the key and filter the key which needs to be deleted i.e.

# Dictionary of strings and int word_freq_dict = key_to_be_deleted = 'at' new_dict = <> for key, value in word_freq_dict.items(): if key is not key_to_be_deleted: new_dictPython dict drop key = value word_freq_dict = new_dict print(word_freq_dict)

We created a new temporary dictionary and then iterate over all the key-value pairs of the original dictionary. While iterating we copied the key-value pair to new temporary dictionary only if the key is not equal to the key to be deleted. Once the iteration is over, we copied the new temporary dictionary contents to the original dictionary. In this approach there is no risk of KeyError etc.

Читайте также:  Java reflexion get private field

Remove a key from a dictionary using items() & Dictionary Comprehension

Using the logic of the previous example we can filter the contents of the dictionary based on key using items() & dictionary comprehension,

word_freq_dict = print(word_freq_dict)

We iterated over the key-value pairs of the dictionary and constructed a new dictionary using dictionary comprehension. But we excluded the pair where key matched the key-to-be-deleted. Then we assigned this new dictionary to the original dictionary. It gave an effect that item from the dictionary is deleted based on key.

Therefore the benefit of this approach is that you need don’t need to worry about the Key Error in case the key does not exist in the dictionary.

Remove a key from a dictionary using del

First select the element from a dictionary by passing key in the subscript operator and then pass it to the del statement. If the key is present in the dictionary then it will delete the key and corresponding value from the dictionary. But if the given key is not present in the dictionary then it will throw an error i.e. KeyError.

Let’s use it to remove the key from the above-mentioned dictionary,

# Dictionary of strings and int word_freq_dict = # Deleting an item from dictionary using del del word_freq_dict['at'] print(word_freq_dict)

It deleted the item from the dictionary where the key was ‘at’. But what if we use a del statement with a key that does not exist in the dictionary, then it can throw KeyError. For example,

key_to_be_deleted = 'where' del word_freq_dict["where"]

Therefore, we should always check if the key exists in the dictionary before trying to delete them using the del keyword to avoid the KeyError,

# If key exist in dictionary then delete it using del. key_to_be_deleted = 'where' if key_to_be_deleted in word_freq_dict: del word_freq_dict["where"] else: print(f'Key is not in the dictionary')
Key where is not in the dictionary

Deleting a key from a dictionary using del keyword and try/except

If we do not want an if check before calling del, then we can use the try/except too. Let’s try to delete a key that does not exist in the dictionary and catch the error too using try/except,

# If key exist in dictionary then delete it using del. key_to_be_deleted = 'where' try: del word_freq_dictPython dict drop key except KeyError: print(f'Key is not in the dictionary')
Key where is not in the dictionary

These were the 6 different ways to remove a Key from a dictionary in python.

Читайте также:  . Определите этот в любую переменную и делайте с ней что хотите.

Share your love

Leave a Comment Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Terms of Use

Disclaimer

Copyright © 2023 thisPointer

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Источник

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.

Читайте также:  Exception java создание своих

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.

Источник

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