热线电话:13121318867

登录
2019-02-18 阅读量: 882
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:
{}
0.0000
2
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子