python随机dict键,并访问它

时间:2017-02-15 22:42:09

标签: python list dictionary random key

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

我已经尝试了更多,无法弄明白。我在访问密钥值

时遇到问题

1 个答案:

答案 0 :(得分:2)

这样的东西?

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

然后随机卡:

>>> suit = random.choice(list(Cards))
>>> card = random.choice(Cards[suit])
>>> card, suit
('King', 'Heart')