Search code examples
pythonlistdictionaryccxt

Dictionaries within a list Python


I'm trying to access some info from a dictionary that sits in a list of dictionaries and I'm really struggling. I'm trying to check my balance on a crypto exchange and when I query it I receive this list of dictionaries:

[{'asset': 'BTC', 'free': '0.50000000', 'locked': '0.00000000'}, 
{'asset': 'LTC', 'free': '0.00000000', 'locked': '0.00000000'}, 
{'asset': 'ETH', 'free': '0.00000000', 'locked': '0.00000000'}, 
{'asset': 'NEO', 'free': '0.00000000', 'locked': '0.00000000'}, 
{'asset': 'BNB', 'free': '0.00000000']

All I'm looking to do is be able to select an asset and return the free amount.

I don't have much experience with dictionaries but I was hoping to be able to do something like:

if asset == 'BTC':
    print(free)

With the desired result in this case to have 0.50000000 returned to me.

Obviously I know that's not going to work but I'm not sure what to do.

For what it's worth I'm using the ccxt Crypto wrapper in python, using fetch_balance(), you'd think there would be a paramter that allows you to select what currency you want to check the balance of but there doesn't seem to be. If anyone knows otherwise though that would also be really helpful!

Many thanks


Solution

  • for dictionary in list:
         if dictionary['asset'] == 'BTC':
              print(dictionary['free'])
    

    That should loop through the list and print each free value for which asset equals 'BTC'.