Python:如何从字典中随机选择的键中获取值



我在这里要做的是从列表中随机选择

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 == subraces.keys():
print(random.choice(subraces.values[subraces.keys]))

但这没有任何回报。我有点不知所措。

谢谢。

您可以简单地在字典上使用.get

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")

这将产生来自给定竞赛的子空间的名称,例如对于Dwarf,输出将是列表中的随机条目,即Hill Dwarf

.get中的字符串值是默认值,如果在子空间映射中找不到键(随机选择(,则会分配该值。

您似乎可以简单地根据密钥设置一个相当于项目长度的随机int

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')

您也可以尝试以下操作:

from random import choice
print(choice(subraces.get(choice(races),[0])) or 'no matches')

最新更新