Python|迭代时从字典中删除项目
Python中的字典是数据值的无序集合,用于像地图一样存储数据值,与其他仅将单个值作为元素保存的数据类型不同,字典包含键:值对。字典的键必须是唯一的并且是不可变的数据类型,例如字符串、整数和元组,但键值可以重复并且可以是任何类型。
让我们看看如何在迭代字典时从字典中删除项目。
方法 #1:使用 del() 方法
Python3
# Creating a dictionary
myDict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
# Iterating through the keys
for key in myDict.keys():
if key == 2:
del myDict[key]
# Modified Dictionary
print(myDict)
Python3
# Creating a dictionary
myDict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
# Using dictionary comprehension to find list
# keys having value in 3.
delete = [key for key in myDict if key == 3]
# delete the key
for key in delete: del myDict[key]
# Modified Dictionary
print(myDict)
Python3
# Creating a dictionary
myDict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
# Using dictionary comprehension
for key in [key for key in myDict if key == 3]: del myDict[key]
# Modified Dictionary
print(myDict)
Python3
# Creating a dictionary
myDict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
# Iterating through the list of keys
for key in list(myDict):
if key == 2:
del myDict[key]
# Modified Dictionary
print(myDict)
Python3
# Creating a dictionary
myDict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
# list of delete keys
delete = []
for key, val in myDict.items():
if val == 'Geeks':
delete.append(key)
for i in delete:
del myDict[i]
# Modified Dictionary
print(myDict)
输出:
{1: 'Geeks', 3: 'Geeks'}
上面的代码在 Python2 上运行良好,但是当我们用 Python3 运行它时,它会抛出以下错误:
for key in myDict.keys():
RuntimeError: dictionary changed size during iteration
此运行时错误表示不允许在迭代期间更改字典的大小(但这是可能的)。现在,让我们看看我们可以在迭代时从字典中删除项目的所有不同方法。
方法#2:使用字典理解
Python3
# Creating a dictionary
myDict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
# Using dictionary comprehension to find list
# keys having value in 3.
delete = [key for key in myDict if key == 3]
# delete the key
for key in delete: del myDict[key]
# Modified Dictionary
print(myDict)
输出:
{1: 'Geeks', 2: 'For'}
其他方式:
Python3
# Creating a dictionary
myDict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
# Using dictionary comprehension
for key in [key for key in myDict if key == 3]: del myDict[key]
# Modified Dictionary
print(myDict)
输出:
{1: 'Geeks', 2: 'For'}
方法 #3:使用 list(myDict)
Python3
# Creating a dictionary
myDict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
# Iterating through the list of keys
for key in list(myDict):
if key == 2:
del myDict[key]
# Modified Dictionary
print(myDict)
输出:
{1: 'Geeks', 3: 'Geeks'}
方法#4:使用键列表
创建一个列表删除并添加我们要删除的所有值的键。遍历该列表中的每个键并继续删除它们。
Python3
# Creating a dictionary
myDict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
# list of delete keys
delete = []
for key, val in myDict.items():
if val == 'Geeks':
delete.append(key)
for i in delete:
del myDict[i]
# Modified Dictionary
print(myDict)
输出:
{2: 'For'}
当 val == 'Geeks' 时,上面的代码将删除所有 key:value 对。由于 'Geeks' 在上述字典中出现两次,因此删除了两个值。