简体   繁体   English

如何从 python 中的字典中提取某些信息?

[英]How to extract certain information from a dict in python?

I'm attempting to write a trading bot algorithm using python.我正在尝试使用 python 编写交易机器人算法。

When the code runs:代码运行时:

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

The output is: output 是:

{'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?如何将 '200.692439 信息提取为浮点值?

owned = float(balance) Where balance is '200.692439' owned = float(balance)其中余额为“200.692439”

  • The value of '200.692439' is not a fixed value and will change. '200.692439'的值不是固定值,会发生变化。 * *

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.到目前为止我所做的:我将 specificID 信息编码到一个文本文档中,然后选择 readline 并将 200.692439 提取到一个元组中。

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我正在寻找一种将元组转换为浮点数的方法,或者寻找一种更简单的方法从字典中提取“200.692439”,以便它可以用作浮点数

You can use您可以使用

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

The [0] is due to your value stored under balance is a list . [0]是由于您存储在balance下的值是一个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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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