looping through list of dictionaries python

核能气质少年 提交于 2021-01-24 09:49:46

问题


I'm trying to access a dictionary within a list and cannot seem to get my for loop to get the key, then the value.

I've placed an image herein so that its easy for me to explain.

so you can see, I would like to navigate to currency = AUD and assign the balance value to a variable, call it aud_balance

for curr in result_bal_qr:
    for k in curr: 
        if curr[k] == 'AUD':

I cannot seem to get the key AUD. so I'm officially stuck.

I've tried to search for dictionary inside of lists etc but no examples of my problem, or maybe even understood my problem wrong (highly likely)

Any help is appreciated.


回答1:


You have a list of dicts. You want to iterate over the list as you are doing, but you don't want to iterate over each dict itself; you just want to check its currency key. So:

for curr in result_bal_qrp:
    if curr['currency'] == 'AUD':
        print(curr['balance'])

Note, if you're going to be iterating over this list multiple times to find different currencies, it may be worth converting it to a simple dict of currency to balance:

curr_dict = {d['currency']: d['balance'] for d in result_bal_qrp}

and now you can do curr_dict['AUD'] to get the Australian balance.




回答2:


You can do with list Comprehension

aud_balance = [d['balance'] for d in l if d['currency'] == 'AUD']


来源:https://stackoverflow.com/questions/51081291/looping-through-list-of-dictionaries-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!