python 示例_带有示例的Python字典pop()方法
python 示例
字典pop()方法 (Dictionary pop() Method)
pop() method is used to remove an item from the dictionary with specified key from the dictionary.
pop()方法用于从字典中删除具有指定键的项。
Syntax:
句法:
dictionary_name.pop(key, value)
Parameter(s):
参数:
key – It represents the specified key whose value to be removed.
key –它代表要删除其值的指定键。
value – It is an optional parameter, it is used to specify the value to be returned if “key” does not exist in the dictionary.
value –这是一个可选参数,用于指定字典中不存在“键”时要返回的值。
Return value:
返回值:
The return type of this method is the type of the value, it returns the value which is being removed.
此方法的返回类型是值的类型,它返回要删除的值。
Note: If we do not specify the value and key does not exist in the dictionary, then method returns an error.
注意 :如果我们未指定值并且字典中不存在键 ,则方法将返回错误。
Example 1:
范例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)
Output
输出量
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.
Demonstrate the example, if key does not exist and value is not specified.
演示该示例,如果键不存在并且未指定value。
Example 2:
范例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')
Output
输出量
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'
翻译自: https://www.includehelp.com/python/dictionary-pop-method-with-example.aspx
python 示例
还没有评论,来说两句吧...