简体   繁体   中英

How to extract certain information from a dict in python?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM