Home > Software design >  Cannot get data from dictionary python
Cannot get data from dictionary python

Time:12-03

I have dictionary like this in variable balance

print(balance)

{'makerCommission': 10, 'takerCommission': 10, 
'balances': [
{'asset': 'A', 'free': '0.01'}, 
{'asset': 'B', 'free': '0.02'}, 
{'asset': 'C', 'free': '0.03'}]}

I want to get value free from B which is 0.02. I try with this code.

print(balance["balances"]['asset']['B'])

It show error.

TypeError: list indices must be integers or slices, not str

How to get data from dictionary ?

CodePudding user response:

Assuming there will only ever be a single asset 'B' in balance['balances']:

print(*[b['free'] for b in balance['balances'] if b['asset'] == 'B'])

Result:

0.02

If you just need the value in a variable:

list_free_for_b_assets = [b['free'] for b in balance['balances'] if b['asset'] == 'B']

CodePudding user response:

the value for the balances key is a list , so you have to access the list items by their index:

print(balance["balances"][1]["free"])

> 0.02

CodePudding user response:

You have to iterate over balances or index it. To get the contents of free.

balance["balances"][1]['free'] #'0.02'

or

for item in balance["balances"]:
    item['free'] # '0.01', '0.02', ...

CodePudding user response:

Python Dictionaries use {}'s. Python Lists use []'s.

Your master object has 3 fields: makerComission and takerComission which are both numbers, and balances which is a list of more JSON Objects. Thus, you must use numbers to access the list.

  • Related