Using dictionaries in Python. Using objects as keys is not working

I have function for looting coins. The main idea is to create a dictionary of coins for each peasant.
I’ve tested this function in pure Python and it’s working like a charm.
But here i have problem that this part coinsForPeasants[nearestPeasant].append[c] isn’t adding anything to the array.

Here is the code:

def peasantPickUpCoin():
    coins = self.findItems()
    peasants = self.findByType("peasant")
    coinsForPeasants = {}
    for f in peasants:
        coinsForPeasants[f] = []
    for c in coins:
        nearestPeasant = c.findNearest(peasants)
    for fr in peasants:
        myCoins = coinsForPeasants[fr]
        coin = fr.findNearest(myCoins)
        if coin:
            self.command(fr, "move", coin.pos)

Here is one problem: .append[c] should be .append(c)

  • .append(c) is a method call, which is what you meant.
  • append[c] is trying to access a property in the append method using the value stored in the c variable, which does not make much sense here, and is a no-op in this case.

Also, I’m not sure if you can use peasants as dictionary keys: I don’t recall whether they are hashable and whether CodeCombat’s Python parser implements the hashable behavior correctly. Give it a try, anyway. :smile:

Thanks. Now code is working )))