I've written some code (or at least tried to) to compare the keys and values of two dictionaries (X and Y) which have the exact same keys but not always the same values, like an x-y coordinate map. The code is supposed to:
- Search for the keys using their values (the specifically needed value to be searched for is provided by a pre-set variable).
- Compare the result keys against each other for matches and return either as output if they match.
I have used Python 2.7 in all my code (I'm quite new to the language), however Python 3 solutions are welcome but not preferred.
Here is the code:
XDict = {
"Jersey" : 0,
"Boston" : -1,
"York" : 0,
"Vegas" : 1,
"Diego" : 0
}
YDict = {
"Jersey" : 0,
"Boston" : 0,
"York" : -1,
"Vegas" : 0,
"Diego" : 1
}
hereX = 0
hereY = 0
def GetLocation(Dict1, Dict2):
locationX = "_"
locationY = "not_"
Location = ''
for placeX, positionX in Dict1.iteritems():
if positionX == hereX:
locationX = placeX
for placeY, positionY in Dict2.iteritems():
if positionY == hereY:
locationY = placeY
if locationX == locationY:
Location = locationX
Location = locationY
print Location
GetLocation(XDict, YDict)
The expected output is "Jersey"
Unfortunately, the code doesn't produce the expected output (produces None
), probably as a result of locationX and locationY never matching.
I've tried using a different form of the above code by removing the last if
block and inserting a while locationX <> locationY:
at the top of the function. But that only causes the code to loop forever.
My larger aim with the code is to write a GetLocation()
function for a Player class which returns the location of the player using x-y coordinates assigned to each location. I understand that I could probably achieve this using a single dictionary and keys with unique values but I would much rather use the x-y coordinates.
I ran out of solutions I could think of and tried searched for solutions elsewhere on the internet including Stack Overflow and have found similar and somewhat helpful suggestions, but these do not solve the problem either including this.
Thank you for your time.