首页 > 解决方案 > 如何用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

标签: pythonpython-3.xlistloopsdictionary

解决方案


因为bucket是一个列表,而不是一个dict,所以你应该先迭代它,并且对于每个dict,迭代它的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

推荐阅读