Skip to content
Advertisement

KeyError: ‘…’ keeps coming back

I keep getting the error and can’t find where the problem lies. I’m trying so I can choose wether I want the attack the creature or both printed and what type the creature is: ‘easy’, ‘medium’ or ‘hard’, I want to store that into a variable.

creature = {'easy': ['chicken', 'slime', 'rat'],
            'medium': ['wolf', 'cow', 'fox'],
            'hard': ['baby dragon', 'demon', 'lesser demi god']
            }

attack = {
    'easy': ['pecks you', 'spits juice at', 'scratches'],
    'medium': ['bites', 'charges at', 'bites'],
    'hard': ['spits sparks of fire at', 'rends', 'smashes']
    }

creature_easy = ['chicken', 'slime', 'rat']

cre = random.choice(creature_easy)
linked = dict(zip(creature[cre], attack[cre]))
cre_type = linked[0]
cre = random.choice(dict(creature))

print(linked[cre])

KeyError: 'rat'

Thanks in advance

Advertisement

Answer

You might want something like:

chosen_level = 'easy'
game_data = dict(zip(creature[chosen_level], attack[chosen_level]))

import random
cre = random.choice(list(game_data))
att = game_data[cre]

print(cre, att) 

Output: rat scratches

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement