簡體   English   中英

如何用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM