当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python Dictionary pop()用法及代码示例


字典 pop() 方法

pop() 方法用于从字典中删除具有指定键的字典中的项目。

用法:

    dictionary_name.pop(key, value)

参数:

  • key- 它表示要删除其值的指定键。
  • value- 可选参数,用于指定字典中不存在“key”时返回的值。

返回值:

该方法的返回类型是值的类型,它返回被移除的值。

注意:如果我们不指定valuekey字典中不存在,则方法返回错误。

范例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)

输出

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.

演示示例,如果键不存在且未指定值。

范例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')

输出

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'


相关用法


注:本文由纯净天空筛选整理自 Python Dictionary pop() Method with Example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。