python遍歷字典刪除元素錯(cuò)誤

今天寫了這么一段代碼,類似于這樣:

d = {'one':1, 'two':2, 'three':3, 'four':4, 'five':5}
for key in d:
    if key == 'three':
        del d[key]

這里報(bào)了一個(gè)這樣的錯(cuò)誤:
RuntimeError: dictionary changed size during iteration;

去查了一下,發(fā)現(xiàn)官方的一個(gè)解釋:
Dictionaries implement a tp_iter slot that returns an efficient iterator that iterates over the keys of the dictionary. During such an iteration, the dictionary should not be modified, except that setting the value for an existing key is allowed (deletions or additions are not, nor is the update() method). This means that we can write

for k in dict: ...
which is equivalent to, but much faster than

for k in dict.keys(): ...
as long as the restriction on modifications to the dictionary (either by the loop or by another thread) are not violated.

也就是說在迭代字典的時(shí)候,每次迭代不得循環(huán)刪除或者更新字典。并且提到for k in dict與for k in dict.keys()功能一樣,并且更快。

這個(gè)錯(cuò)誤的解決方式是將keys轉(zhuǎn)化為列表迭代:

keys = list(d.keys())
for key in keys:
    if key == 'three':
        del(d[key])

字典d返回:
{'one': 1, 'two': 2, 'four': 4, 'five': 5}

歡迎關(guān)注!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 個(gè)人筆記,方便自己查閱使用 Py.LangSpec.Contents Refs Built-in Closure ...
    freenik閱讀 67,953評(píng)論 0 5
  • pyspark.sql模塊 模塊上下文 Spark SQL和DataFrames的重要類: pyspark.sql...
    mpro閱讀 9,932評(píng)論 0 13
  • 函數(shù)調(diào)用 Built-in Functions abs(x) Return the absolute value ...
    叫我七夜閱讀 1,321評(píng)論 0 0
  • 【Day6課后實(shí)踐】這是2018年8月10日“崔律·100天精力和時(shí)間管理訓(xùn)練營”第1.5講的課后實(shí)踐。<實(shí)踐事項(xiàng)...
    孔雀勇士閱讀 224評(píng)論 0 0
  • 最近聽了劉媛媛的《寒門難出貴子》,振奮于“命運(yùn)手里也是有漏網(wǎng)之魚的”?!叭齻€(gè)月考上北大一點(diǎn)都不難”令我對(duì)她的方法有...
    巡野聽風(fēng)閱讀 228評(píng)論 0 0

友情鏈接更多精彩內(nèi)容