簡體   English   中英

RuntimeError:字典在python迭代期間更改了大小

[英]RuntimeError: dictionary changed size during iteration in python

我試圖將F的所有值更改為1,將M的值更改為0,以便創建一個虛擬變量,然后檢查性別在預測結果中的重要性。 我用這種方式創建了字典

Gender_dict = df_new.set_index("Student_ID") ["Gender"].to_dict() 

print (Gender_dict)

並得到:

{366: 'F', 375: 'F', 381: 'F', 391: 'M', 399: 'M', 427: 'M', 429: 'M', 431: 'M', 435: 'M', 444: 'M', 452: 'F', 464: 'M', 472: 'F', 478: 'M', 484: 'F', 487: 'M', 495: 'M', 507: 'F', 1511: 'M', 1512: 'M', 1517: 'F', 1521: 'M', 1526: 'M', 1532: 'F', 1534: 'M', 1540: 'M', 1554: 'M', 1574: 'M', 1576: 'F', 1580: 'M', 1581: 'F', 1592: 'F', 1594: 'F', 1634: 'F', 1638: 'M', 1639: 'M', 1651: 'M', 1672: 'M', 2550: 'M', 7311: 'M', 7313: 'M', 7327: 'M', 7356: 'M', 7361: 'F', 7366: 'M', 7367: 'M', 7372: 'M', 7382: 'M', 7436: 'M', 7440: 'M', 7446: 'M', 8305: 'M', 8312: 'M', 8320: 'M', 8340: 'M', 8342: 'M', 8358: 'M', 8361: 'M', 8363: 'M', 8371: 'M', 8381: 'M', 8383: 'F', 8386: 'F', 8390: 'M', 8391: 'M', 8426: 'M', 8428: 'F', 8435: 'M', 8440: 'M', 8452: 'M', 8457: 'M', 9447: 'M', 9478: 'F', 9486: 'F', 9489: 'M', 9540: 'M', 9545: 'M', 9546: 'M'}

我認為這可能有效

for Student_ID, Gender in Gender_dict.items():
    if Gender == "F":
        Gender_dict[Gender] = "1"
    elif Gender == "M":
        Gender_dict[Gender] = "0"

print (Gender_dict)

但是我得到這個錯誤:

RuntimeError                              
Traceback (most recent call last)
<ipython-input-41-acce392dae9f> in <module>()
      5         #a1[color] = "Tulip"
      6 
----> 7 for Student_ID, Gender Gender_dict.items():

      8     if Gender == "F":
      9         Gender_dict[Gender] = "1"

RuntimeError: dictionary changed size during iteration

我嘗試調整發現的內容以適合自己的目的,但無法使其正常工作。 我還嘗試了幾乎所有可以找到的.replace().apply()方法,但似乎沒有任何效果,因此我認為這可以工作。

任何幫助是極大的贊賞。

尚不清楚您要實現的目標,但是如果您要手動進行一鍵編碼,則關鍵字名稱中只會出現錯字

for Student_ID, Gender in Gender_dict.items(): 
    if Gender == "F": 
        Gender_dict[Student_ID] = "1" 
    elif Gender == "M": 
        Gender_dict[Student_ID] = "0"

如果您創建查找字典:

gender_lookup = { 'F' : 1, 'M' : 0 }

然后,您可以使用字典理解來更新其他字典:

updated = { student_id : gender_lookup[gender] for student_id,gender in Gender_dict.items() } 

在字典上進行迭代時,完全可以更改現有鍵關聯的值。

您不能做的是:添加或刪除密鑰。

您不小心通過使用字典的作為鍵,創建額外的鍵並生成錯誤消息來執行此操作。

通常,最好使用字典理解來覆蓋舊字典,以完成這種完整的dict更新

Gender_dict = {Student_ID:"1" if Gender == "F" else "M" for Student_ID, Gender in Gender_dict.items()}

就像異常消息所暗示的那樣,在迭代字典中的項時,您不能對其進行變異。 您可以改為遍歷該字典的副本:

for Student_ID, Gender in list(Gender_dict.items()):

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM