【问题标题】:List of dictionaries词典列表
【发布时间】:2011-02-21 14:58:13
【问题描述】:

我正在尝试创建一个字典列表,但在我看来,我做错了什么:

所以,我有一个元组列表,如下所示:

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

结果我得到了这个列表:

[{'cat_num': u'cat2', 'name': u'Mew'}, {'cat_num': u'cat2', 'name': u'Mew'}]

谁能告诉我我的错误在哪里?

谢谢。

【问题讨论】:

    标签: python list dictionary


    【解决方案1】:

    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
    

    【讨论】:

      【解决方案2】:

      请记住,dict() 实际上是一个用于构建字典的 Python 内置函数,因此重命名它可能不是一个好主意。为什么不做类似的事情,

      cats = [(u'cat1', u'Matilda'),(u'cat2', u'Mew')]
      lst = [dict(cat_num=c,name=n) for c,n in cats]
      

      【讨论】:

        【解决方案3】:

        首先,您需要为每个元组创建一个字典。在您只使用一个共享字典之前:

        lst = []
        cats = [(u'cat1', u'Matilda'),(u'cat2', u'Mew')]
        for line in cats:
            d = {}
            d['cat_num'] = line[0]
            d['name'] = line[1]
            lst.append(d)
        print lst
        

        【讨论】:

          【解决方案4】:

          由于 dict 已经创建,您将在字典中附加一个 reference 到数组 (lst) 并为 cats 中的每一行更改它。

          要查看此内容,只需 print 每次迭代的字典即可:

          tmp = {}
          final_results = []
          cats = [(u'cat1', u'Matilda'),(u'cat2', u'Mew')]
          for line in cats:
              tmp['cat_num'] = line[0]
              tmp['name'] = line[1]
              print "For", line, "the dictionary is", tmp
              final_results.append(dict)
          
          print "The final list is:", final_results 
          

          您只需每次创建一个新字典,您的问题就会迎刃而解:

          final_results = []
          cats = [(u'cat1', u'Matilda'),(u'cat2', u'Mew')]
          for line in cats:
              final_results.append( \
                  {'cat_num': line[0],
                  'name': line[1]} \
               )
          

          另请参见:"Least Astonishment" and the Mutable Default Argument 了解此行为可能会让您感到惊讶的其他地方。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2023-02-02
            • 1970-01-01
            • 1970-01-01
            • 2011-01-31
            • 2020-05-13
            • 1970-01-01
            • 2021-04-05
            • 2013-01-26
            相关资源
            最近更新 更多