python - 无法从 for 循环中的列表中提取字典

标签 python python-3.x

我想遍历字典列表,但它给我 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 (most recent call last): File "C:/Users/Derick/PycharmProjects/Puthon3_2019/dictionaries2.py", line 14, in for k, v in users_dict.items(): # fails at this line AttributeError: 'str' object has no attribute 'items'

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

print(user_list[0].items())

我给了我-

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

最佳答案

您无法在遍历列表时向列表中添加内容。 user_list.append(v) 将一个字符串添加到字典列表中,它会导致下一次迭代失败,因为它会尝试在字符串中执行 .items()

关于python - 无法从 for 循环中的列表中提取字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55673487/

相关文章:

python - MATLAB 比 Python 快吗?

python - 无法从网页的不同深度抓取相似的链接

python-3.x - pandas.isnull() 不适用于十进制类型?

python - boxPoints 返回负 y 值

python - 扬声器发出简单的蜂鸣声

python - 带有 MultiIndex : check if string is contained in index level 的 Pandas 数据框

python - 如何在 python nltk 中获取 n-gram 搭配和关联?

python - 无法在 EC2(CentOS)上安装 psycopg 3

Python 脚本有效但编译后失败 (Windows)

python - 使用for循环时Python中变量的作用域