python中删除并输出元素28_python如何从字典中删除元素

在Python Dictionary中,可以使用del 关键字删除键。使用del关键字,可以删除字典和整个字典中的特定值。其他的功能,如pop()和popitem()也可用于从词典中删除特定的值和任意值。可以使用clear()方法一次删除字典中的所有项目。嵌套字典中的项目也可以使用del关键字删除,并提供特定的嵌套键和要从该嵌套字典中删除的特定键。

注意 - del Dict将删除整个字典,因此删除后打印它会引发错误。

# Initial Dictionary

Dict = { 5 : 'Welcome', 6 : 'To', 7 : 'Geeks',

'A' : {1 : 'Geeks', 2 : 'For', 3 : 'Geeks'},

'B' : {1 : 'Geeks', 2 : 'Life'}}

print("Initial Dictionary: ")

print(Dict)

# Deleting a Key value

del Dict[6]

print("\nDeleting a specific key: ")

print(Dict)

# Deleting a Key from

# Nested Dictionary

del Dict['A'][2]

print("\nDeleting a key from Nested Dictionary: ")

print(Dict)

# Deleting a Key

# using pop()

Dict.pop(5)

print("\nPopping specific element: ")

print(Dict)

# Deleting a Key

# using popitem()

Dict.popitem()

print("\nPops first element: ")

print(Dict)

# Deleting entire Dictionary

Dict.clear()

print("\nDeleting Entire Dictionary: ")

print(Dict)

输出:Initial Dictionary:

{'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}, 5: 'Welcome', 6: 'To', 7: 'Geeks'}

Deleting a specific key:

{'A': {1: 'Geeks', 2: 'For', 3: 'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}, 5: 'Welcome', 7: 'Geeks'}

Deleting a key from Nested Dictionary:

{'A': {1: 'Geeks', 3: 'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}, 5: 'Welcome', 7: 'Geeks'}

Popping specific element:

{'A': {1: 'Geeks', 3: 'Geeks'}, 'B': {1: 'Geeks', 2: 'Life'}, 7: 'Geeks'}

Pops first element:

{'B': {1: 'Geeks', 2: 'Life'}, 7: 'Geeks'}

Deleting Entire Dictionary:

{}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值