Jeff
Jeff

Reputation: 15

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.

Upvotes: 0

Views: 141

Answers (1)

Trenton McKinney
Trenton McKinney

Reputation: 62453

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'}]}"

Upvotes: 2

Related Questions