python remove key from dictionary -in loop-if exists

python remove key from dictionary :

Hello everyone, this post is related to python dictionary remove key.
Let's start :

In python there are different way to remove key in python dictionary.

following way are used for the Remove Key:

1. Using del

2. Using del and try/ expect

3.Using dict.pop

4. Using pop and try / expect

python remove key from dictionary


we used the dictionary of string and int

# Dictionary of strings and int
wordFreqDic = {
"python": 56,
"tutorial" : 23 ,
"points" : 43,
"learn" : 43
}


if we want to delete the points key from the above code then see How to remove them:

1.Remove  key from dictionary using del function:

del d[key]

del statement removes the given keys from the dictionary.
If sometime given key is not present in dictionary then it will throw KeyErrors.

Use used different another way to delete the key from dictionary from above code

Let's see :


Deleting an entry from dictionary with the help of del key


if "points" in wordFreqDic:
del wordFreqDic["points"]
print("New Dictionary :" , wordFreqDic)

Output:

New Dictionary : {'python': 56, 'toturial': 43, 'learn': 43}

always remember that deleting keys present or not before the deleting the keys

2.Deleting key from dictionary with the help of del and try/except :

If we don not  want of adds if check before calling del functions then  we can use try/except. Let’s try to delete a keys that does not exist in dictionary and catch the errors too.

'''
Use the del and try/ expect to delete key
'''
# If key is not present in dictionary, then del can throw KeyErrors.
try:
del wordFreqDic["pagar"]
except KeyError:
print("Key 'pagar' not found")

Now we want to remove an items from dictionary whose keys is “points”. Let’s see how to do that this:

Remove a keys from dictionary using del

del d[key]

3.Deleting keys from dictionary using del and try/except function:

If we don not  want of add if check before calling delete functions, we can use try/except function. Let’s try to delete a keys that does not exist in dictionary and catch the errors.

'''
delete the key we the help of del and try/expect function
'''
# If key is not present in dictionary, then del can throw KeyErrors
try:
del wordFreqDic["points"]
except KeyError:
print("Key 'points' not found")


Output:

Key 'points' not found

Tags: python remove key from dictionary ,in loop-if exists,iterate dictionary

IF YOU WANT TO LEARN PYTHON CRASH COURSE FOR FREE THEN CLICK HERE.

AND YOU LIKES THIS POST THEN COMMENT AND SHARE.

                                          BEST OF LUCK!!!

Previous
Next Post »

method vs function python-types of method-class in python

method vs function python : Welcome to my article, In this article we are going to see What is method vs function  in python. before going t...