python-3.xobject-slicing

How to print a particular numeric value from a variable content in python


When I run this code:

from luno_python.client import Client
import json

c = Client(api_key_id='<api_id>', api_key_secret='<api_secret>')
try:
  bal = c.get_balances(assets='NGN')
  print(bal)
except Exception as e:
  print(e)

I get this output:

{'balance': [{'account_id': 'xxxxxxxxxxxxxxxx', 'asset': 'NGN', 'balance': '0.000274', 'reserved': '0.00', 'unconfirmed': '0.00'}]} >>>

What I need is anytime I run:

>>>print(bal)

Let me get only this portion as output:

0.000274
{'balance': [{'account_id': 'xxxxxxxxxxxxxxxx', 'asset': 'NGN', 'balance': '`0.000274`', 'reserved': '0.00', 'unconfirmed': '0.00'}]}

I need only the highlighted portion above. Any help will be appreciated.


Solution

  • I don't know if what you get is a dict, but seems like it. Anyways, you just need to get the values by its keys as following:

    bal['balance'][0]['balance']
    

    or much safer to avoid using another try and exception :

    bal.get('balance',[{'balance':'when bal is empty'}])[0].get('balance')