Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Prevent python from indexing array. list indices must be integers

Tags:

python

I've tried researching this with no luck so far. I'm new to python so my apologies I'm sure there's an easy solution to this.

local obj = {
    'button1': [100, 750],
    'button2': {
        'loc': [100, 1750],
        'returns': 2
     }
}

I want some objects to have an extra property of 'returns'. If I'm looping through the object programmatically I have to check that the 'loc' array exists if I want to access it.

if obj[element]['loc'] is not None:
   # get array w obj[element]['loc']
else:
   # get array w obj[element]

The problem is that I get an error:

# list indices must be integers
TypeError: list indices must be integers, not str

I understand why, it's because 'button1' is an array so python starts the lookup index operation, but finds a string instead of an int. However, I need that bracket to search for my ['loc'] property on my next object. I also know that you can't use the '.' operator to index properties in python so I can't do that either...

How could I check if a property exists without it trying to index the previous object's array.

like image 643
alexr101 Avatar asked Sep 11 '26 09:09

alexr101


1 Answers

if isinstance(obj[element], dict) and 'loc' in obj[element]:

Alternatively, you can use try ... except to catch the exception:

try:
    # do something with obj[element]['loc']
except TypeError:
    pass
like image 188
Błotosmętek Avatar answered Sep 12 '26 22:09

Błotosmętek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!