I am trying to use this dictionary in order to conduct a "check" based on the user input. So for instance it would be along the lines of something like it is used below. I think it might need to use a "For" loop?
levels = {
'Closet': {'South': 'Hangar'},
'Hangar': {'North': 'Closet', 'East': 'Westwood'},
'Westwood': {'West': 'Hangar'}
}
location = "Closet"
if location == ("Checking dictionary to see which location it is")
if direction == ("Checking dictionary to see if direction is applicable")
location = ("updated location based on direction used with what is in dictionary levels")
i.e
if location == "Closet"
if direction == "South"
location = "Hangar"
CodePudding user response:
Just taking a stab at what you are looking for here.
def update_location(location, direction, data):
return data.get('location', {}).get(direction, None)
levels = {
'Closet': {'South': 'Hangar'},
'Hangar': {'North': 'Closet', 'East': 'Westwood'},
'Westwood': {'West': 'Hangar'}
}
location = 'Closet'
direction = 'South'
tmp = update_location(location, direction, levels)
if tmp is not None:
location = tmp
It's a dictionary. You don't need to iterate over it to look for a key inside it. You just access the key. The function above will return None if the values passed in are not in the passed in dictionary.
CodePudding user response:
I would write it this way:
if levels.get(location):
possible_direction = levels.get(location)
if possible_direction.get(direction):
location = possible_direction.get(direction)
Or even:
new_location = levels.get(location, {}).get(direction)
if new_location:
location = new_location
Or even:
try:
location = levels[location][direction]
except BaseException:
continue