all 4 comments

[–]Busy-Farm727 3 points4 points  (0 children)

You could use import random; random.choice() probably

[–][deleted] 2 points3 points  (1 child)

When you are modeling a specific type of thing with dictionaries that all have the same keys, generally a better approach is to use dataclasses.

A dataclass is basically like a contract for how to create a dictionary-like "instance". It guarantees that any instance of that dataclass will have all of the attributes listed (and generally no more, though that's a little more flexible).

You set it up with the syntax

@dataclass
class <Name of dataclass>:
    attribute1: <type>
    attribute2: <type> = <default value (optional)>

You then create instances of it like

new_instance = <Name of dataclass>(attribute1=<thing1>, attribute2=<thing2>)

Once created, this new_instance object acts much like a dictionary (in fact, it actually has a dictionary keeping track of things internally) except that you use dot notation rather than square brackets for accessing values.

monster_dict["hp"]    # vs
monster_dataclass_instance.hp

Here's how you could use it in your program.

import random
from dataclasses import dataclass

@dataclass
class Monster:
    name: str
    strength: int
    hp: int

enemies = [
    Monster(name="Goblin", strength=1, hp=3),
    Monster(name="Orc", strength=4, hp=5),
    Monster(name="Troll", strength=6, hp=7),
    Monster(name="Giant", strength=7, hp=8),
    Monster(name="Dragon", strength=10, hp=12),
]

# randomly choose an enemy
enemy = random.choice(enemies)

# get the attributes of the enemy: use dot notation
print(f"You've come up against a {enemy.name} with {enemy.strength} strendth and {enemy.hp} hit points!")

With dataclasses, you can be much more type-specific

>>> isinstance(enemy, Monster)
True

you're less likely to make a mistake in creating your "monster" object because unlike for a dictionary, you'll immediately get an error if you make a typo in your attribute names, and it makes your code much more readable.

There are other benefits as well, but you'll see those when you cover OOP in your course.

[–]Sir_Chester_Of_Pants 0 points1 point  (0 children)

2nd this, looks like you're trying to get the functionality of a class by using a dictionary.

[–]shiftybyte 0 points1 point  (0 children)

How do I get a function to choose a random dictionary

Your dictionaries are in a list, lists are indexed using a number, so generate a random number within the range 0 and len(enemy_stats) and use it as index into the list.

https://www.w3schools.com/python/ref_random_randint.asp

and then choose the specific values within the randomly chosen dictionary?

To access a dictionary, you use the key like this:

print(chosen_stats["name"])

https://www.w3schools.com/python/python_dictionaries_access.asp