python random dict key, and access it [closed]

2020-03-31 06:11发布

import random


Cards = {
    "Spade": ["2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"],
    "Diamond": ["2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"],
    "Club": ["2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"],
    "Heart": ["2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"]

}

for _ in range(55):
    r = random.sample(list(Cards), 1)
    print(r[0])

I've tried plenty more and couldn't figure it out. I'm having problem accessing the value of the key

1条回答
Bombasti
2楼-- · 2020-03-31 06:43

Something like this?

>>> random.choice(list(Cards))
'Heart'

Then a random card:

>>> suit = random.choice(list(Cards))
>>> card = random.choice(Cards[suit])
>>> card, suit
('King', 'Heart')
查看更多
登录 后发表回答