user3728043
user3728043

Reputation: 31

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

Upvotes: 0

Views: 78

Answers (4)

Ishan Joshi
Ishan Joshi

Reputation: 525

You can try this:

for dictionary in bucket:
    for key, val in dictionary.items():
        print(the_key, 'corresponds to', the_value) 

Upvotes: 0

Aaron_ab
Aaron_ab

Reputation: 3758

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

Upvotes: 0

Blckknght
Blckknght

Reputation: 104712

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

Upvotes: 0

Djaouad
Djaouad

Reputation: 22776

Because bucket is a list, not a dict, so you should iterate over it first, and for each dict, 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

Upvotes: 1

Related Questions