循环遍历字典结果错误列表:
AttributeError:'list‘对象没有属性'items’
改变:
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:'list‘对象没有属性'items’
需要产出:
Name: Share-1
Region: ap-south-1
Name: Share-2
Region: us-west-1发布于 2019-09-22 15:45:07
因为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发布于 2019-09-22 15:44:53
你可以试试这个:
for dictionary in bucket:
for key, val in dictionary.items():
print(the_key, 'corresponds to', the_value) 发布于 2019-09-22 15:45:15
您的数据有两个层,因此需要两个循环:
for dct in lst:
for key, value in dct.items():
print(f"{key}: {value}")
print() # empty line between dictshttps://stackoverflow.com/questions/58050798
复制相似问题