Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot get data from dictionary python

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

How to get data from dictionary ?

>Solution :

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']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading