Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中将随机键值对传递给函数/构造函数?_Python_Dictionary_Key Value - Fatal编程技术网

如何在Python中将随机键值对传递给函数/构造函数?

如何在Python中将随机键值对传递给函数/构造函数?,python,dictionary,key-value,Python,Dictionary,Key Value,我有这张纸 cards = { 'A': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10, 'J': 10, 'Q': 10, 'K': 10 } 这个班呢 class Dealer: def __init__(self, hand1, hand2): self.

我有这张纸

cards = {
    'A': 1,
    '2': 2,
    '3': 3,
    '4': 4,
    '5': 5,
    '6': 6,
    '7': 7,
    '8': 8,
    '9': 9,
    '10': 10,
    'J': 10,
    'Q': 10,
    'K': 10
}
这个班呢

class Dealer:

    def __init__(self, hand1, hand2):
        self.hand1 = hand1
        self.hand2 = hand2
我想把一个随机的键值对传递给构造函数。 我不知道怎么。。。 我试过这个

dealer=dealer(卡片,卡片)
但它将通过整个指令

我也试过这个

dealer=dealer(卡片[random.choice(列表(cards.keys()))]),卡片[random.choice(列表(cards.keys())))])


可以得到一个随机值,但我想要一个键值对,或者至少只传递它们的键值?

您走对了。从字典中获取一个键,然后使用它查找对应的值。像这样:

import random

adict = {"1":"4","2":"5"}

k = random.choice(list(adict.keys()))
pair = (k, adict[k])

print(pair)
# output: ('1','4')
random.choice(列表(cards.items())
经销商(*random.choice(列表(cards.items())))