diccionario de Python () Método pop: Aquí, vamos a aprender cómo eliminar un elemento con la clave especificada del diccionario?
Diccionario pop () Método
pop () método se utiliza para eliminar un elemento de diccionario con clave especificada del diccionario.
Sintaxis:
dictionary_name.pop(key, value)
Parámetro (s):
- clave
- – Representa la clave especificada cuyo valor que ser eliminado.
- valor – Es un parámetro opcional, se utiliza para especificar el valor que se devuelve si “clave” no existe en el diccionario.
class valor:
El tipo class de este método es el tipo del valor, devuelve el valor que está siendo eliminado.
Nota : Si no se especifica el valor y clave no existe en el diccionario, entonces el método devuelve un error.
Ejemplo 1:
# Python Dictionary pop() Method with Example
# dictionary declaration
student = {
"roll_no": 101,
"name": "Shivang",
"course": "B.Tech",
"perc" : 98.5
}
# printing dictionary
print("data of student dictionary...")
print(student)
# removing 'roll_no'
x = student.pop('roll_no')
print(x, ' is removed.')
# removing 'name'
x = student.pop('name')
print(x, ' is removed.')
# removing 'course'
x = student.pop('course')
print(x, ' is removed.')
# removing 'perc'
x = student.pop('perc')
print(x, ' is removed.')
# printing default value if key does
# not exist
x = student.pop('address', 'address does not exist.')
print(x)
salida
data of student dictionary...
{'course': 'B.Tech', 'roll_no': 101, 'perc': 98.5, 'name': 'Shivang'}
101 is removed.
Shivang is removed.
B.Tech is removed.
98.5 is removed.
address does not exist.
Demostrar el ejemplo, si la clave no existe y no se especifica valor.
Ejemplo 2:
# Python Dictionary pop() Method with Example
# dictionary declaration
student = {
"roll_no": 101,
"name": "Shivang",
"course": "B.Tech",
"perc" : 98.5
}
# printing dictionary
print("data of student dictionary...")
print(student)
# demonstrating, when method returns an error
# if key does not exist and value is not specified
student.pop('address')
salida
data of student dictionary...
{'course': 'B.Tech', 'name': 'Shivang', 'roll_no': 101, 'perc': 98.5}
Traceback (most recent call last):
File "main.py", line 17, in <module>
student.pop('address')
KeyError: 'address'