PrQ PrQ - 3 months ago 7
Python Question

Get the Key and Value of a dictionary while using random

I'm new to python and I'm trying to make a simple "Game"
I'm trying to get the health of the monsters but only the names come up.
I can do

(random.choice(list(Monster.health.keys())))
and
(random.choice(list(Monster.health.Values())))
to store both the name and health in a variable but I'm using
random
so the name might say 'goblin' but the health may say '50' which is wrong.

How can I store the variable in
random_mon_name_health
and access both 'keys' and 'value'

class Monster:
health = {'goblin': 15, 'giant': 50}


class EncounterM(Monster):
random_mon_name_health = ''

def basic_monster(self):
import random
self.random_mon_name_health = (random.choice(list(Monster.health.keys())))

def test(self):
print(self.random_mon_name_health)


beta_user = EncounterM()
beta_user.basic_monster()
beta_user.test()
# This is only a section of the game that I'm having trouble with

Answer

You only need to call choice once, like so:

class Monster:
    health = {'goblin': 15, 'giant': 50}

class EncounterM(Monster):
    def __init__(self):
        self.random_mon_name = ''
        self.random_mon_health = 0

    def basic_monster(self):
        import random
        self.random_mon_name, self.random_mon_health = \
            random.choice(list(Monster.health.items()))

    def test(self):
        print(self.random_mon_name, self.random_mon_health)


beta_user = EncounterM()
beta_user.basic_monster()
beta_user.test()
Comments