从字典中随机选择一个值,然后随机选择一个键

时间:2019-09-01 18:50:27

标签: python-3.x

我正在尝试用python创建一个命运之轮类型的游戏。我有代码可以从字典中随机选择一个键,但是不确定如何从该特定键中选择一个随机值。

categories = {'Sayings': ['Actions speak louder than words', 'A bird in the hand is worth two in the bush',
                      'All good things come to an end', 'Among the blind the one eyed man is king',
                      'Fortune favors the bold', 'Ignorance is bliss'],'70s Soul Musicians': ['James Brown', 'Sly Stone', 'Aretha Franklin', 'Earth Wind & Fire', 'Stevie Wonder',
                        'Chaka Khan']}

程序选择随机键/类别来让玩家猜测。

randCategory = str(random.choice(list(categories)))
print(randCategory)

2 个答案:

答案 0 :(得分:0)

只需在random.choice上使用categories[randCategory](并且无需将random.choice的结果强制转换为str):

randCategory = random.choice(list(categories))
print(randCategory)
randValue = random.choice(categories[randCategory])
print(randValue)

输出(随机):

70s Soul Musicians
Earth Wind & Fire

答案 1 :(得分:0)

尝试

import random

categories = {
    'Sayings': [
        'Actions speak louder than words',
        'A bird in the hand is worth two in the bush',
        'All good things come to an end',
        'Among the blind the one eyed man is king',
        'Fortune favors the bold',
        'Ignorance is bliss'
    ],
    '70s Soul Musicians': [
        'James Brown',
        'Sly Stone',
        'Aretha Franklin',
        'Earth Wind & Fire',
        'Stevie Wonder','Chaka Khan'
    ]
}

randCategory = str(random.choice(list(categories)))
randValue = str(random.choice(list(categories[randCategory])))

print(randCategory)
print(randValue)
相关问题