[英]How to iterate a list of dictionary with python3
Looping over list of dictionary results error:遍历字典结果列表错误:
AttributeError: 'list' object has no attribute 'items'
AttributeError: 'list' object 没有属性 'items'
Changing:改变:
for the_key, the_value in bucket.items():
to:至:
for the_key, the_value in bucket[0].items():
results the first element.结果是第一个元素。 I would like to capture all elements
我想捕捉所有元素
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)
Actual results:实际结果:
AttributeError: 'list' object has no attribute 'items'
AttributeError: 'list' object 没有属性 'items'
Output wanted: Output 想要:
Name: Share-1
Region: ap-south-1
Name: Share-2
Region: us-west-1
Because bucket
is a list, not a dict
, so you should iterate over it first, and for each d
ict, iterate over it's items
:因为
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: Output:
Name: corresponds to Share-1
Region corresponds to ap-south-1
Name: corresponds to Share-2
Region corresponds to us-west-1
You can try this:你可以试试这个:
for dictionary in bucket:
for key, val in dictionary.items():
print(the_key, 'corresponds to', the_value)
Your data hast two layers, so you need two loops:您的数据有两层,因此您需要两个循环:
for dct in lst:
for key, value in dct.items():
print(f"{key}: {value}")
print() # empty line between dicts
Can do it in a more functional
way, i like it more:可以以更
functional
的方式做到这一点,我更喜欢它:
map(lambda x: print("name: {x}".format(x=x['Name:'])), bucket)
It's lazy, no for
loops, and much more readable它很懒,没有
for
循环,而且可读性更强
Running on:运行:
bucket = [{'Name:': 'Share-1', 'Region': 'ap-south-1'},
{'Name:': 'Share-2', 'Region': 'us-west-1'}]
you'll get (of course you need to consume the map
):你会得到(当然你需要使用
map
):
name: Share-1
name: Share-2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.