简体   繁体   中英

Python: iterating through a list of dictionaries with a for loop

I frequently need to grab Value1 , Value2 , and Value3 from a list of dictionaries like this:

bar = [ {'A':[{'B':{'C':'Value1'}}]},
        {'A':[{'B':{'C':'Value2'}}]},
        {'A':[{'B':{'C':'Value3'}}]} ]

How can I iterate through this list with a for loop to grab the values Value1 , Value2 , and Value3 ? I'm thinking something like:

for x in y:
    # Print Something

Edit: Sometimes 'A' has a list of more than one dictionary. I could end up with something like. What is a good, efficient way to do this? Beginner here.

bar = [ {'A':[{'B':{'C':'Value1'}}]},
    {'A':[{'B':{'C':'Value2'}},{'B':{'C':'Value2b'}}]},
    {'A':[{'B':{'C':'Value3'}},{'B':{'C':'Value3b'}},
    {'B':{'C':'Value3c'}}]} ]
for x in bar:
    print(x['A'][0]['B']['C'])

That is, for each element x in bar , grab the 'A' element of that dictionary, then the first item in that list, the 'B' element of that dictionary, and finally the 'C' element of that dictionary.

The following modification will handle x['A'] having more than one element:

for x in bar:
    for y in x['A']:
        print(y['B']['C']

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