Home > Back-end >  Python: How to get a value from randomly selected key in a dictionary
Python: How to get a value from randomly selected key in a dictionary

Time:07-26

What I'm trying to do here is to get a random choice from a list

races = ['Dragonborn', 'Dwarf', 'Elf', 'Gnome', 'Half-Elf', 'Halfling', 'Half-Orc', 'Human', 'Tiefling']
races_choice = random.choice(races)

and then use that random choice from the list to look at keys in a separate dictionary

subraces = {
'Dwarf': ['Hill Dwarf', 'Mountain Dwarf'],
'Elf': ['High Elf', 'Wood Elf', 'Dark Elf'], 
'Halfling': ['Lightfoot', 'Stout'], 
'Gnome': ['Forest Gnome', 'Rock Gnome'],
}

and if that key matches the random choice, print a random value from that key.

I've tried a few things, but what I'm currently on is this:

if races_choice == subraces.keys():
    print(random.choice(subraces.values[subraces.keys]))

But this returns nothing. I'm a bit at a loss for how to do this.

Thank you.

CodePudding user response:

You can simply use .get on the dictionary.

DEFAULT_VALUE = "default value"
subraces = {
       'Dwarf': ['Hill Dwarf', 'Mountain Dwarf'],
       'Elf': ['High Elf', 'Wood Elf', 'Dark Elf'], 
       'Halfling': ['Lightfoot', 'Stout'], 
       'Gnome': ['Forest Gnome', 'Rock Gnome'],
}

races = ['Dragonborn', 'Dwarf', 'Elf', 'Gnome', 'Half-Elf', 
        'Halfling', 
        'Half-Orc', 'Human', 'Tiefling']

races_choice = random.choice(races)
subrace_options = subraces.get(races_choice, DEFAULT_VALUE)
if subrace_options != DEFAULT_VALUE:
    index = random.randint(0, (len(subrace_options) - 1))
    print(subrace_options[index])
else: 
    print("No subrace for specified race")

This will yield the name of a subrace from a given race e.g. for Dwarf the output will be a random entry in the list i.e. Hill Dwarf.

The string value in the .get is the default value which will be assigned if the key (the random choice) cannot be found in your map of subraces.

CodePudding user response:

It seems like you can simply set a random int equivalent to the length of items accordingly to the key

import random

races = ['Dragonborn', 'Dwarf', 'Elf', 'Gnome', 'Half-Elf', 'Halfling', 'Half-Orc', 'Human', 'Tiefling']

races_choice = random.choice(races)

subraces = {
'Dwarf': ['Hill Dwarf', 'Mountain Dwarf'],
'Elf': ['High Elf', 'Wood Elf', 'Dark Elf'],
'Halfling': ['Lightfoot', 'Stout'],
'Gnome': ['Forest Gnome', 'Rock Gnome']}

if races_choice in subraces:
    print(subraces[races_choice][random.randint(0, len(subraces[races_choice]) - 1)])  # -1 since lists starts from 0, not 1
else:
    print('"'   races_choice   '"', 'has no subraces')

CodePudding user response:

you also can try something like this:

from random import choice

print(choice(subraces.get(choice(races),[0])) or 'no matches')
  • Related