我正在学习python。我试图做出“字典理解”。我很困惑,为什么python告诉我“船尾”是集合而不是字典。
# 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()
输出:
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
答案 0 :(得分:1)
因为您在理解中使用了一个元组,所以它会创建一组元组{(k,v)},其中k和v是键和值。
我认为您想要的是:
poops = {label:Poop(label, category) for label, category in DATA['A'].items()}
主要区别是{k:v for ...}与{(k,v)for ...}