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

Python: Jupyter: How select a specific string in a Dict & List. conventional methods aren't working

Good day Everyone, I am getting Data from an API that looks like this . .

BalR= c.get_balances(assets)
print(BalR)

{'balance': [{'account_id': '619619619619', 'asset': 'LUX', 'balance': '17639852741.00', 'reserved': '619619', 'unconfirmed': '619619'}]}

I am trying to attach just the float of this 'balance': '17639852741.00' to this variable BalR, this is what I’ve tried so far . . .

array2=[]
for i in BalR:
    if "balance" in i:
        array2.append(i)
print(array2)

['balance']

for key, value in BalR.items():
    print(key, ' : ', value)

{'balance': [{'account_id': '619619619619', 'asset': 'LUX', 'balance': '17639852741.00', 'reserved': '619619', 'unconfirmed': '619619'}]}

print(BalR['balance'])

{'balance': [{'account_id': '619619619619', 'asset': 'LUX', 'balance': '17639852741.00', 'reserved': '619619', 'unconfirmed': '619619'}]}

for k, v in BalR.items():
    if k == 'balance':
        print(v)
{'balance': [{'account_id': '619619619619', 'asset': 'LUX', 'balance': '17639852741.00', 'reserved': '619619', 'unconfirmed': '619619'}]}

for k, v in BalR.balance():
    if k == 'balance':
        print(v)
AttributeError                            Traceback (most recent call last)
<ipython-input-7-0885ed5d34e7> in <module>
----> 1 for k, v in BalR.balance():
      2     if k == 'balance':
      3         print(v)

AttributeError: 'dict' object has no attribute 'balance'

print(BalR.balance[2])
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-10-a6a9f44f2008> in <module>
----> 1 print(BalR.balance[2])

AttributeError: 'dict' object has no attribute 'balance'

please advise.

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

>Solution :

You have a list within your dict, you should get the first item on the list and then use the key from the inside dict.

BalR = {'balance': [{'account_id': '619619619619', 'asset': 'LUX', 
'balance': '17639852741.00', 'reserved': '619619', 'unconfirmed': '619619'}]}
BalR['balance'][0]['balance']
'17639852741.00'

Also, I recommend you to use list comprehension if you have more than one dictionary inside balance.

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