python - 如何用python3迭代字典列表
问题描述
遍历字典结果列表错误:
AttributeError:“列表”对象没有属性“项目”
改变:
for the_key, the_value in bucket.items():
至:
for the_key, the_value in bucket[0].items():
结果是第一个元素。我想捕捉所有元素
bucket = [{'Name:': 'Share-1', 'Region': 'ap-south-1'}, {'Name:': 'Share-2', 'Region': 'us-west-1'}]
for the_key, the_value in bucket.items():
print(the_key, 'corresponds to', the_value)
实际结果:
AttributeError:“列表”对象没有属性“项目”
想要的输出:
Name: Share-1
Region: ap-south-1
Name: Share-2
Region: us-west-1
解决方案
因为bucket
是一个列表,而不是一个dict
,所以你应该先迭代它,并且对于每个d
ict,迭代它的items
:
bucket = [{'Name:': 'Share-1', 'Region': 'ap-south-1'}, {'Name:': 'Share-2', 'Region': 'us-west-1'}]
for d in bucket:
for the_key, the_value in d.items():
print(the_key, 'corresponds to', the_value)
输出:
Name: corresponds to Share-1
Region corresponds to ap-south-1
Name: corresponds to Share-2
Region corresponds to us-west-1
推荐阅读
- objective-c - 如何在 Mac (Swift) 上获取当前正在播放的歌曲
- excel - XLSXWriter FILTER():参考其他工作表?
- string - PYQT5 无法将文件夹/文件目录的字符串连接在一起
- javascript - 如何获取 Javascript 中的所有标头?
- python - 自定义 csv writerow 以填充空值
- java - 在控制台上输入用户密码期间,显示星号(*)符号而不是纯文本
- javascript - 使用 CSS 切换导航栏而不是使用 JavaScript/jQuery
- python - 从不同的推文 URL 中查找 ID
- oracle - 当我在报告有一段时间没有运行后运行 ORACLE 12c 报告时,报告会等待 6 分钟,然后才决定执行任何操作
- ipython - 从协程内的 pudb 启动 IPython 交互式 shell 失败