简体   繁体   中英

Dictionary be a Key in a Dictionary Python

I want an O(1) method of checking if I have been in a state. The problem is that a state is defined by the position of a few zoombinis on a map. Zoombini = {(1,1): 0, (2,2):1, (3,3):3} {Position: Zoombini ID} I am using Breadth-First Search and am pushing onto my Queue this dictionary of positions.

dirs = [goNorth, goSouth, goWest, goEast] ## List of functions
zoom = {}
boulders = {}
visited = {} ## {(zoom{}): [{0,1,2},{int}]}
             ## {Map: [color, distance] 0 = white, 1 = gray, 2 = black
n = len(abyss)
for i in xrange(n):
    for j in xrange(n):
        if (abyss[i][j] == 'X'):
            boulders[(i,j)] = True
        elif (isInt(abyss[i][j])):
            zoom[(i,j)] = int(abyss[i][j])      ## invariant only 1 zomb can have this position
        elif (abyss[i][j] == '*'):
              exit = (i, j)
sQueue = Queue.Queue()
zombnum = 0
done = False
distance = 0
sQueue.put(zoom)
while not(sQueue.empty()):
    currZomMap = sQueue.get()
    for zom in currZomMap.iterkeys(): ## zoom {(i,j): 0}
        if not(zom == exit):
            z = currZomMap[zom]
            for fx in dirs: ## list of functions that returns resulting coordinate of going in some direction
                newPos = fx(zom)
                newZomMap = currZomMap.copy()
                del(newZomMap[zom]) ## Delete the old position
                newZomMap[newPos] = z ## Insert new Position
                if not(visited.has_key(newZomMap)):
                    sQueue.put(newZomMap)

My implementation isn't done but I need a better method of checking if I have already visited a state. I could make a function that creates an integer hash out of the dictionary but I don't think that I'd be able to efficiently. Time is also an issue. How can I go about this optimally?

Rather than constructing some fragile custom hash function, I'd probably just use a frozenset :

>>> Z = {(1,1): 0, (2,2):1, (3,3):3}
>>> hash(Z)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
>>> frozenset(Z.items())
frozenset([((2, 2), 1), ((1, 1), 0), ((3, 3), 3)])
>>> hash(frozenset(Z.items()))
-4860320417062922210

The frozenset can be stored in sets and dicts without any problems. You could also use a tuple built from Z.items() but you'd have to ensure it was always stored in a canonical format (say by sorting it first.)

Python doesn't allow mutable keys so I ended up creating a function that hashes my dictionary.

edit--

def hashthatshit(dictionary):
result = 0
i =0
for key in dictionary.iterkeys():
    x = key[0]
    y = key[1]
    result+=x*10**i+y*10**(i+1)+\
             10**(i+2)*dictionary[key]
    i+=3
return result

I used this which is specific to my implementation which is why I originally didn't include it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM