Python: How to get a value from randomly selected key in a dictionary

Question:

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.

Asked By: amryann

||

Answers:

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.

Answered By: William

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')
Answered By: Matrodsilver

you also can try something like this:

from random import choice

print(choice(subraces.get(choice(races),[0])) or 'no matches')
Answered By: SergFSM
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.