FM2020
FM2020

Reputation: 293

Issue with TypeError: list indices must be integers or slices, not dict

For the below code snippet, I receive the error: TypeError: list indices must be integers or slices, not dict.

coin['orderBooks'][i] is indeed a dict, but how can I remove/delete it then? I need to remove from my dataset for further analysis.

#check if bid_price or ask_price exists, if not remove it from orderbooks
for coin in orderbooks:
    for i in coin['orderBooks']:
        bid_price = i['orderBook']['bids']
        ask_price = i['orderBook']['asks']
        if bid_price == [] or ask_price == []:
            del coin['orderBooks'][i]
Traceback (most recent call last):

  File "<ipython-input-47-07d8008d3d9c>", line 6, in <module>
    del coin['orderBooks'][i]

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

Upvotes: 0

Views: 119

Answers (1)

azro
azro

Reputation: 54148

You're misunderstanding, the coin['orderBooks'][i] is not a dict (it even throws the error), the i is an error, you should name it differently, as you access i['orderBook'] you see it's a dict, and to delete it you may use it's index in the array

It would be like :

for coin in orderbooks:
    for idx, val in enumerate(coin['orderBooks']):
        bid_price = val['orderBook']['bids']
        ask_price = val['orderBook']['asks']
        if not bid_price or not ask_price:
            del coin['orderBooks'][idx]

But as remove while iterating is not a really good idea, you may keep the good ones, with a loop comprehension that's easy

for coin in orderbooks:
    coin['orderBooks'] = [val for val in coin['orderBooks'] 
                              if val['orderBook']['bids'] and val['orderBook']['askas']]

Also you can check for empty list directly with its bool value (bool([]) == False)

Upvotes: 1

Related Questions