alexr101 alexr101 - 9 months ago 29
Python Question

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

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']
# get array w obj[element]

The problem is that I get an error:

# list indices must be integers

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.

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

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

    # do something with obj[element]['loc']
except TypeError:
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download