使用 for 循环格式化 python dict

Formatting python dict with a for loop

我正在尝试编写一个遍历 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 无效。除了使用单引号外,只是缺少部分。

假设您有以下任一情况,那么这应该可以让您继续:

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