简体   繁体   中英

How to iterate a list of dictionary with python3

Looping over list of dictionary results error:

AttributeError: 'list' object has no attribute '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'

Output wanted:

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 = [{'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

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:

map(lambda x: print("name: {x}".format(x=x['Name:'])), bucket)

It's lazy, no for loops, and much more readable

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 ):

name: Share-1
name: Share-2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM