我试图创建一个字典列表,但在我看来,我做错了什么:
所以,我有一个元组列表,如下所示:
dict = {}
lst = []
cats = [(u'cat1', u'Matilda'),(u'cat2', u'Mew')]
for line in cats:
dict['cat_num'] = line[0]
dict['name'] = line[1]
lst.append(dict)
print lst
Run Code Online (Sandbox Code Playgroud)
结果我得到这个清单:
[{'cat_num': u'cat2', 'name': u'Mew'}, {'cat_num': u'cat2', 'name': u'Mew'}]
Run Code Online (Sandbox Code Playgroud)
谁能告诉我我的错误在哪里?
谢谢.
移动dct循环内部的定义(不要调用它dict,因为这是类的名称):
lst = []
cats = [(u'cat1', u'Matilda'),(u'cat2', u'Mew')]
for line in cats:
dct = {}
dct['cat_num'] = line[0]
dct['name'] = line[1]
lst.append(dct)
print lst
Run Code Online (Sandbox Code Playgroud)