在Python中,我可以在遍历字典时删除字典中的项吗?
我想从字典中删除不符合特定条件的元素,而不是创建一个全新的字典。以下是一个好的解决方案,还是有更好的方法?
for k, v in mydict.items():
if k == val:
del mydict[k]
在Python中,我可以在遍历字典时删除字典中的项吗?
我想从字典中删除不符合特定条件的元素,而不是创建一个全新的字典。以下是一个好的解决方案,还是有更好的方法?
for k, v in mydict.items():
if k == val:
del mydict[k]
当前回答
您可以首先构建一个要删除的键的列表,然后遍历该列表删除它们。
dict = {'one' : 1, 'two' : 2, 'three' : 3, 'four' : 4}
delete = []
for k,v in dict.items():
if v%2 == 1:
delete.append(k)
for i in delete:
del dict[i]
其他回答
相反,迭代一个副本,例如items()返回的副本:
for k, v in list(mydict.items()):
使用列表(mydict)是最干净的:
>>> mydict = {'one': 1, 'two': 2, 'three': 3, 'four': 4}
>>> for k in list(mydict):
... if k == 'three':
... del mydict[k]
...
>>> mydict
{'four': 4, 'two': 2, 'one': 1}
这对应于列表的并行结构:
>>> mylist = ['one', 'two', 'three', 'four']
>>> for k in list(mylist): # or mylist[:]
... if k == 'three':
... mylist.remove(k)
...
>>> mylist
['one', 'two', 'four']
它们都可以在python2和python3中工作。
你可以使用字典理解法。
D = {k: D [k] for k in D if D [k] != val}
在python3中,迭代dic.keys()将引发字典大小错误。你可以用这种替代方式:
使用python3测试,它工作正常,并且没有引发错误“迭代期间字典更改大小”:
my_dic = { 1:10, 2:20, 3:30 }
# Is important here to cast because ".keys()" method returns a dict_keys object.
key_list = list( my_dic.keys() )
# Iterate on the list:
for k in key_list:
print(key_list)
print(my_dic)
del( my_dic[k] )
print( my_dic )
# {}
在迭代集合时不能修改集合。这种方式是疯狂的——最明显的是,如果你被允许删除和删除当前项,迭代器将不得不移动(+1),而下一次调用next将超出(+2),所以你最终会跳过一个元素(在你删除的元素后面的那个元素)。你有两个选择:
Copy all keys (or values, or both, depending on what you need), then iterate over those. You can use .keys() et al for this (in Python 3, pass the resulting iterator to list). Could be highly wasteful space-wise though. Iterate over mydict as usual, saving the keys to delete in a seperate collection to_delete. When you're done iterating mydict, delete all items in to_delete from mydict. Saves some (depending on how many keys are deleted and how many stay) space over the first approach, but also requires a few more lines.