如何在迭代時從字典中刪除項目? - How to delete items from a dictionary while iterating over it?

問題:

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?
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章