-1

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. Thanks in advance.

  • https://docs.python.org/3/tutorial/datastructures.html#dictionaries – jonrsharpe Jul 11 '20 at 07:11
  • Yes I have tried something like `bal['balance']` and it removed the first balance in my output. Certainly not reflecting on the portion I need – Jideofor5050 Jul 11 '20 at 07:22
  • But closer to it, no? So now you have a list, learn how to use lists. Continue until you have what you do want. Please read e.g. https://sopython.com/wiki/What_tutorial_should_I_read%3F. – jonrsharpe Jul 11 '20 at 07:23

1 Answers1

0

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')
Brad Figueroa
  • 869
  • 6
  • 15
  • This worked great!!! +1 for putting me through in a more concise way. But one more thing I how do I round it off to the nearest 2 decimal place like `0.00` because I tried using it in my code and it threw an error that the amount specified contains decimal, I don't know how to avoid that – Jideofor5050 Jul 11 '20 at 07:55
  • Can you share us what you've tried and what you wanna get ? It'll help us to understand much better :) – Brad Figueroa Jul 11 '20 at 20:03
  • I have solved the issue by doing `balance = float(bal.get('balance',[{'balance':'when bal is empty'}])[0].get('balance')[:4])` and the issue was solved. Thanks a lot for your candid help. I really appreciate. – Jideofor5050 Jul 12 '20 at 01:19