Reputation: 181
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.
Upvotes: 1
Views: 8759
Reputation: 1036
You can do with list Comprehension
aud_balance = [d['balance'] for d in l if d['currency'] == 'AUD']
Upvotes: 0
Reputation: 599610
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.
Upvotes: 5