简体   繁体   English

Python:使用 for 循环遍历字典列表

[英]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:我经常需要从这样的字典列表中获取Value1Value2Value3

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 ?如何使用 for 循环遍历此列表以获取值Value1Value2Value3 I'm thinking something like:我在想类似的事情:

for x in y:
    # Print Something

Edit: Sometimes 'A' has a list of more than one dictionary.编辑:有时“A”有一个以上字典的列表。 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.也就是说,对于bar中的每个元素x ,获取该字典的“A”元素,然后是该列表中的第一项,该字典的'B'元素,最后是字典的'C'元素。

The following modification will handle x['A'] having more than one element:以下修改将处理具有多个元素x['A']

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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