A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/python/python_dictionary_pop_method.htm below:

Python Dictionary pop() Method

Python Dictionary pop() Method

The Python dictionary pop() method is used to remove an item with the specified key from a dictionary and return its value.

It works in the following way −

Syntax

Following is the basic syntax of the Python Dictionary pop() method −

dictionary.pop(key[, default])
Parameters

This method accepts the following parameters −

Return Value

The method returns the value associated with the specified key.

Example 1

In the following example, we remove the key 'b' from the dictionary "my_dict" and retrieve its corresponding value −

my_dict = {'a': 1, 'b': 2, 'c': 3}
value = my_dict.pop('b')
print("The value is:",value)  
print("The dictionary obtained is:",my_dict)  
Output

The output obtained is as follows −

The value is: 2
The dictionary obtained is: {'a': 1, 'c': 3}
Example 2

Here, we try to remove the key 'd' from the dictionary "my_dict". Since the key is not present, it returns the default value "0" instead of raising a KeyError −

my_dict = {'a': 1, 'b': 2, 'c': 3}
value = my_dict.pop('d', 0)
print("The value is:",value)  
print("The dictionary obtained is:",my_dict)  
Output

Following is the output of the above code −

The value is: 0
The dictionary obtained is: {'a': 1, 'b': 2, 'c': 3}
Example 3

In this example, we remove the key 'b' from the dictionary "my_dict" and assigns its corresponding value to the variable "value" −

my_dict = {'a': 1, 'b': 2, 'c': 3}
value = my_dict.pop('b')
print("The value is:",value)    
Output

The result produced is as shown below −

The value is: 2
Example 4

Now, we try to remove the key 'd' from the dictionary "my_dict", which raises a KeyError because the key is not present in the dictionary −

my_dict = {'a': 1, 'b': 2, 'c': 3}
value = my_dict.pop('d')
Output

We get the output as shown below −

Traceback (most recent call last):
  File "/home/cg/root/660e6943bb2bb/main.py", line 2, in <module>
value = my_dict.pop('d')
KeyError: 'd'

python_dictionary_methods.htm


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4