Dictionary value is not changed inside a for loop assignment

前端 未结 2 1306
长发绾君心
长发绾君心 2020-12-12 07:40

So I am learning python using Learn python the hard way. I am trying to develop a inventory system. The goal is to build this into a class that will be pulled by the room

2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-12 07:47

    The value inside your loop is different than the real value of the dictionary. It is just a reference to that value, so when you do value = None you actually change the value of the reference to hold the new value None and not the value of the dictionary.

    To demonstrate it better this is before the assignment inside the for key, value in inventory.iteritems():

    -------            -------------------------
    |value|   -------> |value of the dictionary|
    -------            -------------------------
    

    this is after value = None

                       -------------------------
                       |value of the dictionary|
                       -------------------------
    -------            ------
    |value|   -------> |None|
    -------            ------
    

    As you can see the dictionary value does not change. Only the variable value of the for loop changes. This variable belongs to the scope of the for loop and after that it is discarded.

    An alternative would be instead of value = None to do:

    inventory[key] = None
    

提交回复
热议问题