Py学习  »  Python

runtimeerror:在python中迭代期间字典更改了大小

James Farrelly • 4 年前 • 887 次点击  

我试图将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() 方法我能找到,但似乎什么都不起作用,所以我认为这是可行的。

非常感谢您的帮助。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38391
 
887 次点击  
文章 [ 4 ]  |  最新文章 4 年前
blhsing
Reply   •   1 楼
blhsing    5 年前

正如异常消息所建议的,当您迭代dict的项时,不能改变它。您可以迭代dict的副本:

for Student_ID, Gender in list(Gender_dict.items()):
Jean-François Fabre
Reply   •   2 楼
Jean-François Fabre    5 年前

如果创建查找字典:

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

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

updated = { student_id : gender_lookup[gender] for student_id,gender in Gender_dict.items() } 
Jean-François Fabre
Reply   •   3 楼
Jean-François Fabre    5 年前

在迭代字典时,完全可以 改变 现有的 关键。

您不能做的是:添加或删除键。

你不小心用了 价值 以字典为键,创建额外的键并生成错误消息。

一般来说,这种 完整的听写更新 最好使用字典理解,覆盖旧字典:

Gender_dict = {Student_ID:"1" if Gender == "F" else "M" for Student_ID, Gender in Gender_dict.items()}
Slam
Reply   •   4 楼
Slam    5 年前

目前还不完全清楚你想要达到什么样的目标,但是如果你用手进行一次热编码,你只需要在密钥名中输入错别字。

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