[英]How to iterate over list of sets and converting it to a dictionary in Python3
[英]How to iterate a list of dictionary with python3
遍历字典结果列表错误:
AttributeError: 'list' object 没有属性 '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' object 没有属性 'items'
Output 想要:
Name: Share-1
Region: ap-south-1
Name: Share-2
Region: us-west-1
因为bucket
是一个列表,而不是一个dict
,所以你应该首先迭代它,并且对于每个d
,迭代它的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)
Output:
Name: corresponds to Share-1
Region corresponds to ap-south-1
Name: corresponds to Share-2
Region corresponds to us-west-1
你可以试试这个:
for dictionary in bucket:
for key, val in dictionary.items():
print(the_key, 'corresponds to', the_value)
您的数据有两层,因此您需要两个循环:
for dct in lst:
for key, value in dct.items():
print(f"{key}: {value}")
print() # empty line between dicts
可以以更functional
的方式做到这一点,我更喜欢它:
map(lambda x: print("name: {x}".format(x=x['Name:'])), bucket)
它很懒,没有for
循环,而且可读性更强
运行:
bucket = [{'Name:': 'Share-1', 'Region': 'ap-south-1'},
{'Name:': 'Share-2', 'Region': 'us-west-1'}]
你会得到(当然你需要使用map
):
name: Share-1
name: Share-2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.