Home > Mobile >  Assistance with key error in python dictionary
Assistance with key error in python dictionary

Time:12-08

So first off I want to thank everybody for helping me previously. After digging deeper into the previous problems of my understanding , I had a lot of people assist me with a better understanding. So I apologize in advance to for asking so many questions, but its honestly how I learn and I feel as though it will make me a much better coder in the longer run.

In saying that I understand the issues I am having with the code on the bottom. Its basically because I am removing the key=item when the item is picked up. Then if the user accidently uses the same "Get "Item"" or anything revolving around "Get" it just comes back with an error saying key error: Item

So I was wondering if anybody had any ideas on how to fix this?

    # print a main menu and the commands
    print("Halo Text Adventure Game")
    print("Collect 6 items to win the game, or be eaten by Gravemind.")
    print("Move commands: go South, go North, go East, go West")
    print("Add to Inventory: get 'item name'")


def movement_between_locations(location, action, rooms):
    location = rooms[location][action]
    return location


def get_item(location, action, rooms, equipment):
    equipment.append(rooms[location]['item'])
    del rooms[location]['item']
    return rooms, equipment, location , action

def main():
    rooms = {
        'Halo': {'South': 'The Silent Cartographer', 'North': 'Assault on the Control Room',
                 'East': 'Pillar of Autumn', 'West': 'The Library'},
        'The Silent Cartographer': {'North': 'Halo', 'East': '343 Guilty Spark', 'item': 'Camo'},
        '343 Guilty Spark': {'West': 'The Silent Cartographer', 'item': 'Energy Sword'},
        'The Maw': {'South': 'Pillar of Autumn', 'item': 'Gravemind'},
        'The Library': {'East': 'Halo', 'item': 'Frag Grenade'},
        'Assault on the Control Room': {'South': 'Halo', 'East': 'Two Betrayals', 'item': 'Rocket Launcher'},
        'Two Betrayals': {'West': 'Assault on the Control Room', 'item': 'Plasma Grenade'},
        'Pillar of Autumn': {'West': 'Halo', 'North': 'The Maw', 'item': 'Over Shield'},
    }

    location = 'Halo'
    equipment = []
    show_instructions()

    while True:

        # Checking user_action and connecting to new room, or if they typed get item, item is received
        if location == "The Maw":
            # User wins
            if len(equipment) == 6:
                print("You won")
                break
            else:
                print("You lost")
                break
        # Display players room, equipment,
        print("You are in the "   location)
        print(equipment)
        print("-" * 20)
        # This will tell user if there is an item in the room
        if location != 'The Maw' and 'item' in rooms[location].keys():
            print('You see the {}'.format(rooms[location]['item']))
        action = input("Enter your move:").title().split()
        if len(action) >= 2 and action[1] in rooms[location].keys():
            location = movement_between_locations(location, action[1], rooms)
            continue
        elif len(action[0]) == 3 and action[0] == "Get" and ' '.join(action[1:]) in rooms[location]['item']:
            print("You picked up the {}!".format(rooms[location]['item']))
            print('-' * 20)
            get_item(location, action, rooms, equipment)
            continue
        else:
            print("invalid input")
            continue


main() ```

CodePudding user response:

You can check before get it:

def get_item(location, action, rooms, equipment):
    try:
       item = rooms[location]['item']
    except:
       return # do something here
    equipment.append(item)
    del rooms[location]['item']
    return rooms, equipment, location , action

CodePudding user response:

When removing items from a dictionary, you can use the dict.pop method, which contains a default argument for what to return if the key isn't present:

def get_item(location, action, rooms, equipment):
    # Gets removed from the dictionary here
    # and if the key doesn't exist, it returns the second arg (None)
    item = rooms[location].pop('item', None)

    if item is not None:
        equipment.append(item)

    return rooms, equipment, location , action

However, you don't actually need most of your arguments. You just need rooms and location, and you can just return the item and append it to equipment later:

# Get rid of unnecessary arguments
def get_item(location, rooms):
    # Gets removed from the dictionary here
    # and if the key doesn't exist, it returns the second arg (None)
    return rooms[location].pop('item', None)


# Wherever you call `get_item` is how this code gets used
item = get_item(rooms, location)

if item is not None:
    equipment.append(item)
  • Related