【问题标题】:Not able to extact dictionary from a list in a for loop无法从 for 循环中的列表中提取字典
【发布时间】:2019-04-14 17:13:21
【问题描述】:

我想遍历字典列表,但它给了我AttributeError

这是我的代码 -

user_list = []
new_user = { 'last': 'fermi',
             'first': 'enrico',
             'username': 'efermi', }
user_list.append(new_user)


new_user = { 'last': 'fermi2',
             'first': 'enrico2',
             'username': 'efermi2', }
user_list.append(new_user)

for users_dict in user_list:
    for k, v in users_dict.items(): # fails at this line
        if(k == 'username'):
            user_list.append(v)

例外 -

Traceback(最近一次调用最后一次):文件 “C:/Users/Derick/PycharmProjects/Puthon3_2019/dictionaries2.py”,行 14、在 for k, v in users_dict.items(): # failed at this line AttributeError: 'str' object has no attribute 'items'

但是,如果我像下面这样访问字典工作正常 -

print(user_list[0].items())

我给我 -

dict_items([('last', 'fermi'), ('first', 'enrico'), ('username', 'efermi')])

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    您不能在迭代列表时添加到列表中。 user_list.append(v) 将一个字符串添加到字典列表中,它会导致下一次迭代失败,因为它试图在一个字符串中执行 .items()

    【讨论】:

      【解决方案2】:

      您正在附加您正在迭代的相同列表。在下一次迭代中,for 循环从该列表中选择一个字符串而不是一个 dict,这就是您得到错误的地方。

      【讨论】:

        【解决方案3】:

        正如其他人所说,您将v(一个字符串)附加到您正在迭代的由字典组成的列表中,以字符串和字典的混合结尾,这是不可取的。我认为这是一种错字,可以通过简单的方式修复:

        usernames = []
        for users_dict in user_list:
            for k, v in users_dict.items(): # fails at this line
                if(k == 'username'):
                    usernames.append(v)
        usernames
        >>> ['efermi', 'efermi2']
        
        

        或更好:

        usernames = [x["username"] for x in user_list]
        

        【讨论】:

          【解决方案4】:

          原因是您在迭代中将str 添加到user_list

          user_list.append(v)
          

          在 python 中,允许在遍历list 的同时进行编辑,list 将迭代附加到它的新内容。

          比如我们可以用listbfs,同时遍历和编辑。

              for node in bfs:
                  bfs += node.successor
              return bfs
          

          【讨论】:

            猜你喜欢
            • 2019-01-29
            • 2017-04-05
            • 2022-11-17
            • 1970-01-01
            • 2021-02-15
            • 2018-02-16
            • 1970-01-01
            • 2020-10-11
            • 1970-01-01
            相关资源
            最近更新 更多