Home > OS >  How to access dict inside list
How to access dict inside list

Time:12-13

I searched for similar questions with no luck. I am trying to get the data inside a, under 'bids' and 'asks'. Here is the code:

response = requests.get(book_url, params={'instrument_name': 'BTC_USDT', 'depth': 2})
resp = response.json()
print('resp: ', type(resp))
a  = resp['result']['data']

This is what a looks like:

[{'bids': [['17015.36', '1.86922', '6'], ['17014.91', '0.01175', '1']],
  'asks': [['17015.37', '0.98410', '3'], ['17015.54', '0.01469', '1']],
  't': 1670869985838}]

If I try getting 'bids' I get the following error:

a['bids']
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[102], line 1
----> 1 a['bids']

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

What am I doing wrong?

CodePudding user response:

a is a list with one element which is the dict you want.

a['bids'] is asking for a dict element with a key of 'bids'.

Try a[0]['bids'].

CodePudding user response:

The variable a is a list. In your example it contains just one element. Considering that it might contain multiple elements you could print them as follows:

print(*[_a.get('bids') for _a in a], sep='\n')

For the data shown this gives:

[['17015.36', '1.86922', '6'], ['17014.91', '0.01175', '1']]
  • Related