以函数作为参数的python dict.fromkeys

以函数作为参数的python dict.fromkeys,python,dictionary,Python,Dictionary,我需要将test\u input中的数据与classes进行分组,即如果test\u input中的两个值相同,则它们应该具有相同的类 我尝试创建字典,但无法了解如何进行类管理: @pytest.mark.parametrize("test_input,expected", [ ([23,33,33,53,63,73,83,93,103], 'dictwithclass'), ]) def test_colorize(test_input, expected): clas

我需要将
test\u input
中的数据与
classes
进行分组,即如果
test\u input
中的两个值相同,则它们应该具有相同的类

我尝试创建字典,但无法了解如何进行类管理:

@pytest.mark.parametrize("test_input,expected", [
    ([23,33,33,53,63,73,83,93,103], 'dictwithclass'),
])
def test_colorize(test_input, expected):    
    classes = ("colore1","colore2","colore3","colore4","colore5","colore6","colore7","colore8","colore9","colore10")

    insiemi=set(test_input)

    result = dict.fromkeys(insiemi, classi)
应输出:

{33:“colore1”,83:“colore2”,53:“colore3”,103:“colore4”,73: “colore5”,23:“colore6”,93:“colore7”,63:“colore8”}

dict.fromkeys()
将所有键设置为相同的单个值。您不能使用它来设置多个不同的值

使用
zip()
将键和值配对,然后将生成的
(键,值)
对序列传递给
dict()
直接键入:

classes = ('colore1', 'colore2', 'colore3', 'colore4', 'colore5', 'colore6', 'colore7', 'colore8', 'colore9', 'colore10')
result = dict(zip(set(test_input), classes))
请注意,因为
set()
对象是无序的,所以您无法确定此处的键与类的对应关系。对于整数值,解释器调用之间的顺序是稳定的,但在不同的Python版本中可能有所不同

演示:

以上假设不存在超过10个唯一密钥;最好在此处生成类名:

result = {key: 'colore{}'.format(i) for i, key in enumerate(set(test_input), 1)}
这将使用
enumerate()
函数对集合中的每个元素进行编号(从1开始),然后使用该编号生成类名

result = {key: 'colore{}'.format(i) for i, key in enumerate(set(test_input), 1)}