Python Att Dictionary Pop
# Python2.x Python Dictionary pop() Method
[ Python Dictionary](#)
* * *
## Description
The Python dictionary `pop()` method removes the value associated with the given key from the dictionary and returns the removed value.
## Syntax
The syntax for the `pop()` method is:
pop(key[,default])
## Parameters
* **key** - The key to be removed.
* **default** - The value to return if the key `key` does not exist.
## Return Value
Returns the removed value:
* If `key` exists - removes the corresponding element from the dictionary.
* If `key` does not exist - returns the specified default value `default`.
* If `key` does not exist and the default value `default` is not specified - raises a `KeyError` exception.
## Example
The following example demonstrates the usage of the `pop()` method:
## Example
#!/usr/bin/python
# -*- coding: UTF-8 -*-
site={'name': '','alexa': 10000,'url': 'www.'}
element =site.pop('name')
print('The popped element is:')
print(element)
print('The dictionary is:')
print(site)
Output:
The popped element is:The dictionary is:{'url': 'www.', 'alexa': 10000}
If the key to be deleted does not exist, an exception will be raised:
## Example
#!/usr/bin/python
# -*- coding: UTF-8 -*-
site={'name': '','alexa': 10000,'url': 'www.'}
element =site.pop('nickname')
print('The popped element is:')
print(element)
print('The dictionary is:')
print(site)
Output:
Traceback (most recent call last): File "test.py", line 6, in element = site.pop('nickname')KeyError: 'nickname'
You can set a default value to avoid the exception:
## Example
#!/usr/bin/python
# -*- coding: UTF-8 -*-
site={'name': '','alexa': 10000,'url': 'www.'}
element =site.pop('nickname','Non-existent key')
print('The popped element is:')
print(element)
print('The dictionary is:')
print(site)
Output:
The popped element is:Non-existent key The dictionary is:{'url': 'www.', 'alexa': 10000, 'name': 'xe8x8fx9cxe9xb8x9fxe6x95x99xe7xa8x8b'}
* * Python Dictionary](#)
YouTip