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

I've tried researching this until no luck. I'm new to python, so I'm sorry, I'm pretty sure this is a simple solution.

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

      

I want some objects to have an additional "returns" property. If I loop through the object programmatically, I have to check if 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 I am getting the error:

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

      

I understand why, because 'button1' is an array, so python runs the search index operation, but finds a string instead of an int. However, I need this brace to find my ['loc'] property on my next object. I also know that you cannot use '.' operator for indexing properties in python, so I cannot do that ...

How can I check if a property exists without trying to index the previous array of objects.

+3


source to share


2 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

      

+6


source


You can try this:



if type(obj[element]) is dict and obj[element]['loc'] is not None:

      

+1


source







All Articles