简体   繁体   中英

How to extract data from a dictionary?

I am trying to get the asset/free/locked fields along with the corresponding data to populate into columns. Currently, I can only get the balances column where these fields fall.

Here is the data format. I don't need anything before 'balances'. Thinking if I could remove this part of the string maybe then the columns would be created? Or if there is a another way to do this?

'{'makerCommission': 10, 'takerCommission': 10, 'buyerCommission': 0, 'sellerCommission': 0, 'canTrade': True, 'canWithdraw': True, 'canDeposit': True, 'updateTime': 1595872633345, 'accountType': 'MARGIN', 'balances': [{'asset': 'BTC', 'free': '0.00000000', 'locked': '0.00000000'}, {'asset': 'LTC', 'free': '0.00000000', 'locked': '0.00000000'}, {'asset': 'ETH', 'free': '0.00000000', 'locked': '0.00000000'}...'

The code so far to get the balances is:

account = client.get_account()

assets = pd.DataFrame(account, columns = ['balances'])

Any help appreciated. Got me stumped.

from ast import literal_eval
import pandas as pd

# if account is a string
assets = pd.json_normalize(literal_eval(account), 'balances')

# if account is a dict
assets = pd.json_normalize(account, 'balances')

# display(assets)
  asset        free      locked
0   BTC  0.00000000  0.00000000
1   LTC  0.00000000  0.00000000
2   ETH  0.00000000  0.00000000

Sample Data as a str

data = "{'makerCommission': 10, 'takerCommission': 10, 'buyerCommission': 0, 'sellerCommission': 0, 'canTrade': True, 'canWithdraw': True, 'canDeposit': True, 'updateTime': 1595872633345, 'accountType': 'MARGIN', 'balances': [{'asset': 'BTC', 'free': '0.00000000', 'locked': '0.00000000'}, {'asset': 'LTC', 'free': '0.00000000', 'locked': '0.00000000'}, {'asset': 'ETH', 'free': '0.00000000', 'locked': '0.00000000'}]}"

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