Home > database >  Python: Jupyter: How select a specific string in a Dict & List. conventional methods aren't wor
Python: Jupyter: How select a specific string in a Dict & List. conventional methods aren't wor

Time:03-16

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.

CodePudding user response:

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.

  • Related