Python 2.7 听写理解-为什么调试器告诉我我的听写是一个集合?

Python 2.7 听写理解-为什么调试器告诉我我的听写是一个集合?,python-2.7,Python 2.7,我正在学习python。我试图做一个“dict理解”,我不明白为什么python告诉我“poops”是一个集合而不是dict # dictionary<string, tuple<string, string>> DATA = { 'A': ( ('Label1', 'Category1'), ('Label2', 'Category1'), ('Label3', 'Category2'), ('La

我正在学习python。我试图做一个“dict理解”,我不明白为什么python告诉我“poops”是一个集合而不是dict

# dictionary<string, tuple<string, string>>
DATA = {
    'A': (
        ('Label1', 'Category1'),
        ('Label2', 'Category1'),
        ('Label3', 'Category2'),
        ('Label4', 'Category2'),
    ),
    'B': (
        ('Label1', 'Category1'),
        ('Label2', 'Category1'),
        ('Label3', 'Category2'),
        ('Label4', 'Category2'),
    ),
    'C': (
        ('Label1', 'Category1'),
        ('Label2', 'Category1'),
        ('Label3', 'Category2'),
        ('Label4', 'Category2'),
    ),
    'D': (
        ('Label1', 'Category1'),
        ('Label4', 'Category2'),
    )
}


class Poop:
    def __init__(self, label, category):
        self.label = label
        self.category = category


def main():

    my_dictionary = {'A': 1, 'B': 2}
    print "{}".format(type(my_dictionary))

    poops = {
        (label, Poop(label, category))
        for label, category in DATA['A']
    }

    print "{}".format(type(poops))
    for _, poop in poops:
        print "{}".format(type(poop))


if __name__ == "__main__":
    main()
#字典
数据={
“A”:(
('Label1','Category1'),
(“标签2”,“类别1”),
('Label3','Category2'),
('Label4','Category2'),
),
“B”:(
('Label1','Category1'),
(“标签2”,“类别1”),
('Label3','Category2'),
('Label4','Category2'),
),
“C”:(
('Label1','Category1'),
(“标签2”,“类别1”),
('Label3','Category2'),
('Label4','Category2'),
),
“D”:(
('Label1','Category1'),
('Label4','Category2'),
)
}
船尾等级:
定义初始(自我、标签、类别):
self.label=标签
self.category=类别
def main():
我的字典={'A':1,'B':2}
打印“{}”。格式(键入(我的字典))
粪便={
(标签,船尾(标签,类别))
对于标签,数据中的类别['A']
}
打印“{}”。格式(类型(poops))
对于u3;,在船尾中的船尾:
打印“{}”。格式(类型(poop))
如果名称=“\uuuuu main\uuuuuuuu”:
main()
输出:

pydev debugger: process 1008 is connecting

Connected to pydev debugger (build 191.6605.12)
<type 'dict'>
<type 'set'>
<type 'instance'>
<type 'instance'>
<type 'instance'>
<type 'instance'>

Process finished with exit code 0
pydev调试器:进程1008正在连接 已连接到pydev调试器(build 191.6605.12) 进程已完成,退出代码为0
因为你在理解中使用了一个元组,所以它创建了一组元组{(k,v)},其中k和v是键和值

我想你想要的是:

poops = {label:Poop(label, category) for label, category in DATA['A'].items()}

主要的区别是{k:v for…}和{(k,v)for…}

当我这样做时,下一个for循环给出了一个错误:“文件'main.py',第43行,main for,poop in poops:ValueError:toom value to unpack”nm,我想我用poops.items()修复了它,是的,我错过了,完全正确。要获取键、值或两者,请使用.keys()、.values()或.items()。