【问题标题】:Add a key to my dictionary if condition is met如果满足条件,请在我的字典中添加一个键
【发布时间】:2020-10-14 10:43:53
【问题描述】:

我有一个非常简单的字典,包含三个项目。 如果满足条件,我想遍历字典并在其中添加一个新项目。在这种情况下,如果弹出“绿色”键。 我已经尝试了一段时间,似乎无法弄清楚。我不断收到“RuntimeError: dictionary changed size during iteration”

我的代码:

color_dict = {"red" : "color", "green" : "color" , "three" : "not color"}

for i in color_dict:
    if i == "green":
        color_dict.update({"blue" : "color"})

我是初学者,所以我可能不知道更高级的方法。有人可以帮我解决一个简单的问题吗?我觉得我错过了一些小而重要的东西。

【问题讨论】:

    标签: dictionary for-loop


    【解决方案1】:

    替换此行

    color_dict.update({"blue" : "color"})
    

    下面一行

    color_dict['blue'] = 'color'
    

    修改后生效。

    至于为什么你的代码可能不起作用,这是因为字典的update() 方法只能更新字典中已经存在的键的值。例如,您可以更新three 的值:

    color_dict.update({"three" : "color"})
    

    输出:

    >>> color_dict
    {'red': 'color', 'green': 'color', 'three': 'not color', 'blue': 'color'}
    

    【讨论】:

      猜你喜欢
      • 2017-09-21
      • 1970-01-01
      • 2011-03-10
      • 2012-12-25
      • 1970-01-01
      • 2016-02-03
      • 2014-06-16
      • 1970-01-01
      相关资源
      最近更新 更多