Search code examples
pythonarrayslistdictionarycoordinate

(Dictionary) storing keys with x,y in Python


What I am trying to do is to store an x,y value with a key. For example, in my case, I need it so that once any x,y has reached the value of 3, some process happens.

Here is what I have tried: However, this gives me an error, as I am unable to store lists within dictionaries.

dictionary= {}
player = [0,0]

def Checking():
    if player in dictionary:
        dictionary[[player]] +=1
        print("repopulate", dictionary)
    else:
        dictionary[player] = 0
        print(dictionary)
    if dictionary.get(player) >= 3:
        print("It is done!")

EDIT: Sorry about the lack of clarity in the question. The player variable is the user input of where the user wishes to move within the x,y given. There are multiple treasures, and if the user is to chose a position x,y which is the same as a treasure x,y; then +1 should be added to that treasure. Once a treasure reaches 3, it should be diminished.


Solution

  • I think you want to use player as your key, and the count as the value of that key:

    >>> treasure_hits = {}
    >>> player = (0,0)
    >>> try:
    ...   treasure_hits[player] += 1
    ... except KeyError:
    ...   treasure_hits[player] = 0
    ... 
    >>> treasure_hits
    {(0, 0): 0}
    >>> 
    >>> try:
    ...   treasure_hits[player] += 1
    ... except KeyError:
    ...   treasure_hits[player] = 0
    ... 
    >>> treasure_hits
    {(0, 0): 1}
    >>> 
    

    Making treasure_hits a tuple instead of a list allows it to be used as a key since it is immutable