問題:
Is it legitimate to delete items from a dictionary in Python while iterating over it?在迭代它時從 Python 中的字典中刪除項目是否合法?
For example:例如:
for k, v in mydict.iteritems():
if k == val:
del mydict[k]
The idea is to remove elements that don't meet a certain condition from the dictionary, instead of creating a new dictionary that's a subset of the one being iterated over.這個想法是從字典中刪除不滿足特定條件的元素,而不是創建一個新字典,它是被迭代的一個子集。
Is this a good solution?這是一個很好的解決方案嗎? Are there more elegant/efficient ways?有沒有更優雅/有效的方法?
解決方案:
參考一: https://stackoom.com/question/MarS參考二: How to delete items from a dictionary while iterating over it?