Dictionary value is not changed inside a for loop assignment

前端 未结 2 1294
长发绾君心
长发绾君心 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
    
    0 讨论(0)
  • 2020-12-12 07:56

    zbs is correct, you're only changing the value of the pointer to the dict value. However, you're making this way too hard:

    #This is the inventory in this room
    inventory = {'Miniature Fusion Warhead': 'desk',
                 'knife':'bed'}
    player_inventory = set()
    
    def take(item):
      if item in inventory:
        print("You picked up the {}".format(item))
        player_inventory.add(item)
        del inventory[item]
    
      else:
        print("That item doesn't exist")
    
    while True:
      print('')
      print("Inventory: " + ', '.join(player_inventory))
      for k,v in inventory.items():
        print("You see a {} on the {}".format(k, v))
    
      print("What do you want to pick up?")
      ui = raw_input("> ").split()
      verb = ui[0]
      item = ' '.join(ui[1:])
      if verb == 'take':
        if item:
          print("You take the {}".format(item))
          take(item)
        else:
          print("That item doesn't exist")
      else:
        print("That's not an action")
    
    0 讨论(0)
提交回复
热议问题