-1

I'm attempting to write a trading bot algorithm using python.

When the code runs:

specificID = auth_client.get_balances(assets = 'ZAR' )
print(specificID)

The output is:

{'balance': [{'account_id': '7008143899323135806', 'asset': 'ZAR', 'balance': '200.692439', 'reserved': '0.00', 'unconfirmed': '0.00'}]}

My question is:

How do I extract the '200.692439 information into a float value?

owned = float(balance) Where balance is '200.692439'

  • The value of '200.692439' is not a fixed value and will change. *

What I have done so far : I coded the specificID information into a text document and then chose to readline and extract the 200.692439 into a tuple.

f = open("demo.txt", "w")
f.write(str(specificID))
f.close()

with open('demo.txt', 'r') as handle:
    first_line = handle.readline()
    tuple_balance = first_line[79],first_line[80],first_line[81],first_line[82],first_line[83],first_line[84],first_line[85]

I'm looking for a way to convert the tuple to float or for a simpler way to extract '200.692439' from the dict so it can be used as a float

mhhabib
  • 2,975
  • 1
  • 15
  • 29
RennY
  • 15
  • 3
  • First, don't just use every tag that seems relevant -- in this case don't use both Python-3.x and Python-2.7 tag unless you specifically want the code to run on both (in this case specify that clearly in the question) – user202729 Feb 18 '21 at 03:05
  • And (1) if the solution below is correct then you'd better learn Python carefully rather than copying snippets from random stack overflow answers, (2) provide a [example]. In this case you can likely hard code the obtained result **into** the code. – user202729 Feb 18 '21 at 03:07
  • Pretty much a duplicate of [Python Accessing Nested JSON Data - Stack Overflow](https://stackoverflow.com/questions/23306653/python-accessing-nested-json-data) , although the "JSON" name in title is confusing. – user202729 Feb 18 '21 at 03:38

1 Answers1

1

You can use

float(d['balance'][0]['balance'])

The [0] is due to your value stored under balance is a list.


d['balance']
#[{'account_id': '7008143899323135806', 'asset': 'ZAR', 'balance': '200.692439', 'reserved': '0.00', 'unconfirmed': '0.00'}]


d['balance'][0]
#{'account_id': '7008143899323135806', 'asset': 'ZAR', 'balance': '200.692439', 'reserved': '0.00', 'unconfirmed': '0.00'}

float(d['balance'][0]['balance'])
#200.692439
PacketLoss
  • 5,561
  • 1
  • 9
  • 27