【问题标题】:Formatting python dict with a for loop使用 for 循环格式化 python dict
【发布时间】:2021-07-25 10:22:02
【问题描述】:

我正在尝试编写一个通过 assets (BTC, EOS) 和 available_balance (0.00087168, 0) 的 for 循环。 assets 工作,但是我无法访问 available_balance。我怎么能用 json 来实现它。

import json 

pairs= '''
({
  'ext_code': '',
  'rate_limit_status': 118,
  'result': {
      'BTC': {'available_balance': 0.00087168, 'cum_realised_pnl': 7.288e-05, 'equity': 0.00087168, 'given_cash': 0},
      'EOS': {'available_balance': 0, 'cum_realised_pnl': 0, 'equity': 0, 'given_cash': 0}
  },
  'ret_code': 0,
  'ret_msg': 'OK',
  'time_now': '1619987733.732306'}
<bravado.requests_client.RequestsResponseAdapter object at 0x000002D6F7FEB808>)
'''
data = json.loads(pairs)
Wallet_balance = data[0]['result']
for assets in balance:
    print("Asset: ", assets, " Balance: ", assets['available_balance'])

预期输出:

Asset: BTC Balance: 0.00087168
Asset: EOS Balance: 0

pprint 输出:

({'ext_code': '',
  'ext_info': '',
  'rate_limit': 120,
  'rate_limit_reset_ms': 1620081183677,
  'rate_limit_status': 117,
  'result': {'BTC': {'available_balance': 0.00087168,
                     'cum_realised_pnl': 7.288e-05,
                     'equity': 0.00087168,
                     'given_cash': 0,
                     'occ_closing_fee': 0,
                     'occ_funding_fee': 0,
                     'order_margin': 0,
                     'position_margin': 0,
                     'realised_pnl': 0,
                     'service_cash': 0,
                     'unrealised_pnl': 0,
                     'used_margin': 0,
                     'wallet_balance': 0.00087168},
             'EOS': {'available_balance': 0,
                     'cum_realised_pnl': 0,
                     'equity': 0,
                     'given_cash': 0,
                     'occ_closing_fee': 0,
                     'occ_funding_fee': 0,
                     'order_margin': 0,
                     'position_margin': 0,
                     'realised_pnl': 0,
                     'service_cash': 0,
                     'unrealised_pnl': 0,
                     'used_margin': 0,
                     'wallet_balance': 0},
             'ETH': {'available_balance': 0.03362706,
                     'cum_realised_pnl': -7.41e-06,
                     'equity': 0.03362706,
                     'given_cash': 0,
                     'occ_closing_fee': 0,
                     'occ_funding_fee': 0,
                     'order_margin': 0,
                     'position_margin': 0,
                     'realised_pnl': 0,
                     'service_cash': 0,
                     'unrealised_pnl': 0,
                     'used_margin': 0,
                     'wallet_balance': 0.03362706},
             'USDT': {'available_balance': 0,
                      'cum_realised_pnl': 0,
                      'equity': 0,
                      'given_cash': 0,
                      'occ_closing_fee': 0,
                      'occ_funding_fee': 0,
                      'order_margin': 0,
                      'position_margin': 0,
                      'realised_pnl': 0,
                      'service_cash': 0,
                      'unrealised_pnl': 0,
                      'used_margin': 0,
                      'wallet_balance': 0},
             'XRP': {'available_balance': 0,
                     'cum_realised_pnl': 0,
                     'equity': 0,
                     'given_cash': 0,
                     'occ_closing_fee': 0,
                     'occ_funding_fee': 0,
                     'order_margin': 0,
                     'position_margin': 0,
                     'realised_pnl': 0,
                     'service_cash': 0,
                     'unrealised_pnl': 0,
                     'used_margin': 0,
                     'wallet_balance': 0}},
  'ret_code': 0,
  'ret_msg': 'OK',
  'time_now': '1620081183.700541'},
 <bravado.requests_client.RequestsResponseAdapter object at 0x0000016DC011F888>)

【问题讨论】:

  • 您的“json”输入是否使用单引号?

标签: json python-3.x for-loop format


【解决方案1】:

请注意,您的 json 无效。除了使用单引号之外,它只是缺少部分。

假设您有以下任何一项,那么这应该可以帮助您:

import json
import ast

## -----------------------------
## I have valid json
## -----------------------------
pairs_double_quoted = '''
[{
  "ext_code": "",
  "rate_limit_status": 118,
  "result": {
      "BTC": {"available_balance": 0.00087168, "cum_realised_pnl": 7.288e-05, "equity": 0.00087168, "given_cash": 0},
      "EOS": {"available_balance": 0, "cum_realised_pnl": 0, "equity": 0, "given_cash": 0}
  },
  "ret_code": 0,
  "ret_msg": "OK",
  "time_now": "1619987733.732306"
}]
'''
## -----------------------------

## -----------------------------
## I have something else that still looks hopeful
## -----------------------------
pairs_single_quoted = '''
({
  'ext_code': '',
  'rate_limit_status': 118,
  'result': {
      'BTC': {'available_balance': 0.00087168, 'cum_realised_pnl': 7.288e-05, 'equity': 0.00087168, 'given_cash': 0},
      'EOS': {'available_balance': 0, 'cum_realised_pnl': 0, 'equity': 0, 'given_cash': 0}
  },
  'ret_code': 0,
  'ret_msg': 'OK',
  'time_now': '1619987733.732306'
})
'''
## -----------------------------

## -----------------------------
## one or the other depending on if you have proper json (double) quotes
## -----------------------------
data = json.loads(pairs_double_quoted)
#data = [ast.literal_eval(pairs_single_quoted)]
## -----------------------------

## -----------------------------
## data is a list so we likely want to go though each item on the list
## if you only want the first item then use
## data_item = data[0]
## -----------------------------
for data_item in data:
    ## -----------------------------
    ## for each key value pair in the result dict print something
    ## -----------------------------
    for asset_key, asset_value in data_item["result"].items():
        print("Asset: {} Balance: {}".format(asset_key, asset_value["available_balance"]))
    ## -----------------------------
## -----------------------------

根据您的更新,您所拥有的数据准确无误:

pairs_single_quoted = '''
({
  'ext_code': '',
  'rate_limit_status': 118,
  'result': {
      'BTC': {'available_balance': 0.00087168, 'cum_realised_pnl': 7.288e-05, 'equity': 0.00087168, 'given_cash': 0},
      'EOS': {'available_balance': 0, 'cum_realised_pnl': 0, 'equity': 0, 'given_cash': 0}
  },
  'ret_code': 0,
  'ret_msg': 'OK',
  'time_now': '1619987733.732306'
}<bravado.requests_client.RequestsResponseAdapter object at 0x000002D6F7FEB808>)
'''

出于某种原因,您可能想走ast 路线:

import re
import ast

## -----------------------------
## I have something else that still looks hopeful
## -----------------------------
pairs_single_quoted = '''
({
    'ext_code': '',
    'ext_info': '',
    'rate_limit': 120,
    'rate_limit_reset_ms': 1620081183677,
    'rate_limit_status': 117,
    'result': {
        'BTC': {'available_balance': 0.00087168, 'cum_realised_pnl': 7.288e-05, 'equity': 0.00087168, 'given_cash': 0, 'occ_closing_fee': 0, 'occ_funding_fee': 0, 'order_margin': 0, 'position_margin': 0, 'realised_pnl': 0, 'service_cash': 0, 'unrealised_pnl': 0, 'used_margin': 0, 'wallet_balance': 0.00087168},
        'EOS': {'available_balance': 0, 'cum_realised_pnl': 0, 'equity': 0, 'given_cash': 0, 'occ_closing_fee': 0, 'occ_funding_fee': 0, 'order_margin': 0, 'position_margin': 0, 'realised_pnl': 0, 'service_cash': 0, 'unrealised_pnl': 0, 'used_margin': 0, 'wallet_balance': 0},
        'ETH': {'available_balance': 0.03362706, 'cum_realised_pnl': -7.41e-06, 'equity': 0.03362706, 'given_cash': 0, 'occ_closing_fee': 0, 'occ_funding_fee': 0, 'order_margin': 0, 'position_margin': 0, 'realised_pnl': 0, 'service_cash': 0, 'unrealised_pnl': 0, 'used_margin': 0, 'wallet_balance': 0.03362706}
    },
    'ret_code': 0,
    'ret_msg': 'OK',
    'time_now': '1620081183.700541'},
    <bravado.requests_client.RequestsResponseAdapter object at 0x0000016DC011F888>)
 '''
## -----------------------------

## -----------------------------
## a regex wizard would do this via re.sub()
## -----------------------------
pattern = re.compile(r"^(.*),.*<bravado.*$", re.DOTALL)
text_in = re.findall(pattern, pairs_single_quoted)[0] + ")"
data = [ast.literal_eval(text_in)]
## -----------------------------

## -----------------------------
## data is a list so we likely want to go though each item on the list
## if you only want the first item then use
## data_item = data[0]
## -----------------------------
for data_item in data:
    ## -----------------------------
    ## for each key value pair in the result dict print something
    ## -----------------------------
    for asset_key, asset_value in data_item["result"].items():
        print("Asset: {} Balance: {}".format(asset_key, asset_value["available_balance"]))
    ## -----------------------------
## -----------------------------

这应该会导致:

Asset: BTC Balance: 0.00087168
Asset: EOS Balance: 0
Asset: ETH Balance: 0.03362706

【讨论】:

  • 我已经更新了这个问题,我忘了把&lt;bravado.requests_client.RequestsResponseAdapter object at 0x000002D6F7FEB808&gt;放在json dict的末尾。我收到错误消息:TypeError: 'RequestsResponseAdapter' object is not subscriptable. If you could take a look at it I would appreciate it.
  • 它说元组对象在编辑后的代码上没有属性拆分
  • 我将pairs_single_quoted 设为tuple 类型,而不是string 类型,因为我是从网络服务器获取的。
  • 我想我需要确切地看到目前返回的文本。看起来我所拥有的并不是你所得到的。例如,&lt;bravado.requests_client 之前是否真的有一个逗号?
  • 很抱歉给您带来了麻烦,我将使用pprint 更新整个 json 输出,这样您就可以看到整个内容了
猜你喜欢
  • 1970-01-01
  • 2020-02-22
  • 1970-01-01
  • 1970-01-01
  • 2013-05-28
  • 2018-05-08
  • 1970-01-01
  • 1970-01-01
  • 2015-04-15
相关资源
最近更新 更多