Home > Enterprise >  How to iterate over a dictionary in Python to move in different directions
How to iterate over a dictionary in Python to move in different directions

Time:12-13

I am creating a text based game for my homework. I have been able to everything except move between rooms using the directions: North, South, East and West. I have not worked with dictionaries much at all and I am struggling. I do not understand how to do this especially in the bedroom with 2 different directions. Directions: The game should prompt the player to enter commands to move between rooms #The dictionary links a room to other rooms.

rooms = {
        'Great Hall': {'South': 'Bedroom'},
        'Bedroom': {'North': 'Great Hall', 'East': 'Cellar'},
        'Cellar': {'West': 'Bedroom'}
    }

CodePudding user response:

location = 'Great Hall'

print(f'You are currently in {location}.')
move = input('Enter a direction to move: ')
if move in rooms[location]:
    location = rooms[location][move]
    # location is now e.g. 'Bedroom'
else:
    print('You cannot go that way.')

CodePudding user response:

This is basically an answer to the OP's comment with reference to @John Gordon's Answer

In the question, rooms is a 2D dictionary (dictionary inside a dictionary). When we use rooms[location], for example rooms['Bedroom'], it picks up the corresponding dictionary of moves from the key 'Bedroom' i.e. {'North': 'Great Hall', 'East': 'Cellar'}, similarly if we use rooms[location][move], it picks up the value of the move from the dictionary that was returned. So if I use rooms['Bedroom']['North'] it will return 'Great Hall'.

I hope this solved your query

  • Related