python 遍历 list中 dict,遍历字典python列表

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.

mAqZd.png

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.

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值