[英]Python: iterating through a list of dictionaries with a for loop
我經常需要從這樣的字典列表中獲取Value1
、 Value2
和Value3
:
bar = [ {'A':[{'B':{'C':'Value1'}}]},
{'A':[{'B':{'C':'Value2'}}]},
{'A':[{'B':{'C':'Value3'}}]} ]
如何使用 for 循環遍歷此列表以獲取值Value1
、 Value2
和Value3
? 我在想類似的事情:
for x in y:
# Print Something
編輯:有時“A”有一個以上字典的列表。 我最終可能會得到類似的東西。 有什么好的、有效的方法來做到這一點? 初學者在這里。
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'])
也就是說,對於bar
中的每個元素x
,獲取該字典的“A”元素,然后是該列表中的第一項,該字典的'B'
元素,最后是該字典的'C'
元素。
以下修改將處理具有多個元素x['A']
:
for x in bar:
for y in x['A']:
print(y['B']['C']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.