Python dictionary pop

In this Python tutorial, we will discuss Python dictionary pop. Here we will also cover the below examples:

  • Python dictionary pop method
  • Python dictionary pop examples
  • Python dictionary pop vs del
  • Python dictionary pop multiple keys
  • Python dictionary pop vs popitem
  • Python dictionary pop key and value
  • Python dictionary pop if exists
  • Python dictionary pop item
  • Python dictionary pop last element
  • Python dictionary pop during iteration
  • Python pop dictionary from list

Python dictionary pop

  • In Python to remove an element from the dictionary, we can apply the pop() method. This method checks the condition if a key or value does not contain in the dictionary then it returns a key error else if a key is available in the dictionary it will remove an item and return its value.
  • The pop() method is an in-built function in Python that deletes the specified key or value from the dictionary.

Syntax:

Here is the Syntax of the dictionary pop() method

dict.pop(key,default)
  • This method consists of few parameters:
    • Key: The key parameter is used to be delete from the dictionary.
    • Default: If the key is not available in the dictionary then it will return the default value.

Return: The pop() method return

  • If a key is present – pop() element from dictionary
  • If a default value is not specified in an argument then it will raise a key error

Source Code:

Let’s take an example and check how to remove an element from a dictionary by using the pop() method

my_dict = {'george':92,'john':14,'Micheal':25}

rem_key = my_dict.pop('john')
print("remove key",rem_key)
print(my_dict)

Here is the Screenshot of the following given code

python dictionary pop
python dictionary pop

Read: Python dictionary contains

Python dictionary pop method

The dictionary pop() method helps the user to delete the key element from the dictionary and return its value.

Let’s take an example and check if a key is not available in the dictionary

new_dictionary = {'China':234,'Africa':145,'Australia':178}

new_key = new_dictionary.pop('Germany')
print(new_key)

In the above code, we have initialized a dictionary and put the elements in the form of key-value pairs. In this example, we will check if a key is not available in the dictionary. To solve this problem we can use the pop() method to check the condition. As you can see, the pop() method passes a key as an argument, but the ‘Germany‘ key is not available in the dictionary, raising a key error.

Here is the execution of the following given code

Python dictionary pop method
Python dictionary pop method

Read: Python dictionary comprehension

Python dictionary pop vs del

The main difference between pop() and del() is

  • In Python ‘del’ is a keyword and pop() is a method. In the case of del() it does not return any value while in the case of the pop() method if we want to remove a key from the dictionary you can use pop() and it will return the value.
  • In the pop() method if you don’t mention the last parameter in pop() method arguments then it will returns a key error. While in the case of del() if a key is not present in the dictionary then it will return a key error.
  • In Python to remove objects from the list using the index, we can easily use the ‘del’ keyword and pop() method.
  • The main difference between these two methods is the ‘del’ keyword does not return anything while the pop() method returns the removed element from the dictionary.

Syntax:

Here is the Syntax of the ‘del’ keyword

del dict["key"]

Example:

Let’s take an example and check how to use the del keyword in a dictionary

my_dict = {'Python':79,'java':26,'Sql':17}

del my_dict['java']
print(my_dict)

Here we are going to create a program that deletes a key from a dictionary using the del keyword. In this example, we have to remove a ‘java’ key from the dictionary. To do this task we will use the del keyword.

Here is the execution of the following given code

python del keyword
python del keyword

Read: Python dictionary find a key by value

Pop() method example

Source Code:

emplo_dict = [
	{ "emp_id": 26, "emp_name": "Oliva", "emp_age": 36, "emp_res": True },
	{ "emp_id": 98, "emp_name": "George", "emp_age": 42, "emp_res": True },
	{ "emp_id": 37, "emp_name": "james", "emp_age": 98, "emp_res": False }
]
for z in emplo_dict:
	new_key = z.pop("emp_res", None)

	if new_key != None:
		print("emp_res key has been deleted for the {} employee.".format(z["emp_name"]))
	else:
		print("No key has been deleted for the {} employee.".format(z["emp_name"]))

print(emplo_dict)

In the above code, we have created a list and contains three dictionaries. Each dictionaries stores four keys and value pairs. We want to remove the ’emp res‘ key from the dictionary using the pop() method in this example. Now we will check if the “emp_res” key has been removed from the dictionary using the ‘if statement’ in Python. Let us see if new_key has a value other than none that means our key is deleted.

Here is the execution of the following given code

python pop example
python pop example

Read: Python convert dictionary to list

Python dictionary pop multiple keys

  • In Python to remove multiple keys from the dictionary, we can easily apply pop() and list comprehension methods.
  • In this example, we just use the pop() method to remove an element from the dictionary.

Example:

Let’s take an example and check how to remove multiple keys in a dictionary using the pop() method

my_dictionary = {'Cyprus' : 1, 'Cuba' : 2, 'Africa' : 3, 'England' : 4, 'china' : 5}

mul_keys = ['Cuba', 'Africa', 'china']
[my_dictionary.pop(key) for key in mul_keys]
print(" Dictionary after Remove multiple keys : ",my_dictionary)

In the above code, we have created a dictionary and contains key-value pair elements. Now initialize a list and store the elements which we want to remove from the dictionary. After that use the list comprehension method to iterate the list items and print the result.

Here is the Screenshot of the following given code

Python dictionary pop multiple keys
Python dictionary pop multiple keys

Read: Python dictionary remove

Alternative example of how to remove multiple keys in Python dictionary

Here you can see the combination method of pop() and for loop method. This method helps the user to iterate each key of the variable. In this example, the elements get removed from the given list of keys.

new_dictionary = {'Egypt': 67, 'Estonia': 13, 'Geogria': 87, 'Hungary': 98};
rem_ele = ('Egypt', 'Estonia', 'Hungary');
for i in rem_ele:
    new_dictionary.pop(i);
print("Available dictionary after remove keys",new_dictionary);

Here is the output of the following given code

remove multiple keys using pop in python
remove multiple keys using pop in python

Read: Python While loop condition

Python dictionary pop vs popitem

  • In Python, these two methods are used to delete elements from a dictionary. The pop() method deletes the element in the form of key-value pair whereas if we want to delete the last key-value pair element from the dictionary by using the popitem() method.
  • In the python, 3.7 version removes the specific last key-value pair element from the dictionary and displays the result in the form of a tuple.
  • The main difference between pop() and popitem() is that the pop() element can remove an element with a specific key while in the case of popitem() we will delete the last entered element from the dictionary.
  • In the popitem() method if we want to remove an item but the dictionary is empty then it will raise an error whereas in the pop() method if the key is not present in the dictionary it will display a key error.

Syntax:

Here is the Syntax of popitem() method

dictionary.popitem()

Note: It does not take any arguments

Source Code of popitem() example

new_dict = {'Mathew':56, 'Hayden':78, 'oliva': 27, 'gilchrist': 189}

output = new_dict.popitem()
print('Remove key = ', output)
print('New original dictionary: ', new_dict)

Here is the implementation of the following given code

Python dictionary pop vs popitem
Python dictionary pop vs popitem

Read: Python dictionary length

Pop() method example

Source Code:

you_dict = {
  'student_id': 78,
  'stu_post': 'Python developer'
}

rem_key = you_dict.pop('stu_post', None)
print(rem_key)
print("Dictionary after remove key",you_dict)

In the above code, we have to use two arguments in a dictionary.pop() method. In this example, we will check if the key exists in the dictionary it will remove the element else it will display None.

Here is the output of the following given code

python dict pop vs popitem method
python dict pop vs popitem method

Python dictionary pop key and value

  • In Python to remove key and value pairs from the dictionary, we can apply the pop() method.
  • To solve this problem first we create a dictionary and assign them key-value pair elements. Now use the pop() method to remove a specific key-value pair from the dictionary.

Syntax:

Here is the Syntax of pop() method

dict.pop(key[, default])

Source Code:

my_new_dict = {"b":18,"c":10,"u":19,"r":67}

delete_key = my_new_dict.pop("c")
print("Original dictionary",my_new_dict)
print("Remove key-value pair",delete_key)

Execution:

Python dictionary pop key and value
Python dictionary pop key and value

Read: Python Dictionary index

Python dictionary pop if exists

  • Let us see how to check if a key contains in a Python dictionary.
  • If the specified key is not available in the dictionary and no default value is present in the pop() method argument then it will raise a key error.
  • Let’s take an example and check how to remove an element that is not available in the dictionary by using the pop() method and also we will check the condition if we are not passing a default value in the pop() method argument then what will happen.

Source Code:

you_dictionary = {"v":14,"s":10,"z":190,"l":167}

remov_new_key = 'q'
if remov_new_key in you_dictionary:
    you_dictionary.pop(remov_new_key)
else:
    print("Key not exist in dictionary:",remov_new_key)

Here is the output of the following given code

Python dictionary pop if exists
Python dictionary pop if exists

Read: Python dictionary initialize

Python dictionary pop item

In a Python dictionary, the popitem() method deletes an element and returns it into a tuple pair form. In the popitem() method it always returns into last in first out order form that means it removes specific last key-value pair element from the dictionary.

Example:

Let’s take an example and check how to delete an element from the Python dictionary by using the popitem() method

stdent_dict = {'George': 46, 'John':345, 'Micheal': 169, 'Potter': 543}  

b = stdent_dict.popitem()  
print("Delete last pair",b)  
print("New dictionary",stdent_dict)  

Here is the implementation of the following given code

Python dictionary pop item
Python dictionary pop item

Read: Python dictionary filter

Python dictionary pop last element

  • To remove the last element from the python dictionary we can easily use the pop() method.

Source Code:

my_dictionary = {'e':189,'h':192,'f':223}

rem_las = my_dictionary.pop('f')
print("remove last element",rem_las)
print(my_dictionary) 

In the above code, we have initialized a dictionary and put the elements in the form of key-value pairs. In this example, we will check how to delete a last element from the dictionary. To solve this problem we will declare a variable ‘rem_las’ and assign a pop method in which we pass a key element argument ‘f’. Now it will check the condition if the key is present in the dictionary. it will display the result that the last element is removed from the dictionary.

Here is the Screenshot of the following given code

Python dictionary pop last element
Python dictionary pop last element

Read: Python Dictionary sort

Python dictionary pop during iteration

  • To iterate over a python dictionary and delete items by using the pop() method.

Example:

to_dict = {"j":14,"n":16,"l":12,"z":15}
for new_key in dict(to_dict):
    if to_dict[new_key] % 2 == 0:
        to_dict.pop(new_key)
print(to_dict)

In this example, you can see that we have iterate all the key-value pairs and put the condition if the value is even it will remove from the dictionary whereas in odd number elements it will display in the output.

Here is the Screenshot of the following given code

Python dictionary pop during iteration
Python dictionary pop during iteration

Read: Python dictionary values to list

Python pop dictionary from list

  • In Python to remove elements from a list of dictionaries, we can apply del and loop method.
  • In this example it will compare the condition if the key value is available in the dictionary it will remove the whole dictionary pair.

Source Code:

student_list = [{"student_id" :56, "address" : "England"},
             {"student_id" : 78, "address" : "Germany"},
             {"student_id" :923, "address" : "France"}]

for m in range(len(student_list)):
    if student_list[m]['student_id'] == 923:
        del student_list[m]
        break
print ("List after remove: ",student_list)
Python pop dictionary from list
Python pop dictionary from the list

You may also like reading the following articles:

In this Python tutorial, we will discuss Python dictionary pop. Here we will also cover the below examples:

  • Python dictionary pop method
  • Python dictionary pop examples
  • Python dictionary pop vs del
  • Python dictionary pop multiple keys
  • Python dictionary pop vs popitem
  • Python dictionary pop key and value
  • Python dictionary pop if exists
  • Python dictionary pop item
  • Python dictionary pop last element
  • Python dictionary pop during iteration
  • Python pop dictionary from list