python - 运行时错误: dictionary changed size during iteration in python

标签 python dictionary iteration

我正在尝试将 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() 方法,但似乎没有任何效果,所以我认为这会起作用。

非常感谢任何帮助。

最佳答案

在字典上进行迭代时,完全可以更改现有键关联的值。

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

您不小心使用字典的作为键,创建了额外的键并生成了错误消息。

通常,这种完整字典更新最好使用字典理解来完成,覆盖旧字典:

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

关于python - 运行时错误: dictionary changed size during iteration in python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52988095/

相关文章:

python - 无法在 us-central1 中更新加密 key

sorting - 我如何使用mapreduce在hadoop集群上实现自适应mergesort

python - 通过 4 个索引同时迭代

python - 如何检查一个项目是否是迭代的最后一个?

python - 在opencv(python)中阅读视频

python - 使用 Beautiful Soup 获取特定的 tr 元数据

python - 在 python 中以按键方式将字典列表一起添加的最快方法

c++ - 迭代地编写递归代码

python - Plot.ly 饼图结果精度

python - 如何找到一个键的多个值的平均值?