INT and STR issue in data find from JSON in Python

I’m trying to find data from my JSON, and return some of it’s values. This apparently is giving me some issues between str/int and I cannot for the life of me figure it out.

Here is the data set:

data = {
    "ports": [
            {
                    "port": "A",
                    "sensor": 4,
                    "door": "pin0",
                    "lights": "pin3"
            },
            {
                    "port": "Q",
                    "sensor": 22,
                    "door": "pin2",
                    "lights": "pin44"
            }
    ]
}

And here is the code:

def detect(sens):
        for i in data:
                if i["sensor"] == sens:
                        print(i["port"])
                        print(i["door"])
                        print(i["lights"])
                        break

The error that it returns is:

Traceback (most recent call last):   File "tester.py", line 45, in
detect
    if i["sensor"] == sens: TypeError: string indices must be integers, not str

As the numers are not within “”, I figured they would be integers, but apparently not. I tried forcing them as such with int(4), but that also didn’t seem to do it. Forcing the i[“sensor”] as an interger with: if int(i[“sensor”]) == sens: also did nothing.

Any help is appreciated!

Answer

You want to iterate over data["ports"], not data itself.

def detect(sens):
    for p in data["ports"]:
        if p["sensor"] == sens:
            print(p["port"])
            print(p["door"])
            print(p["lights"])
            break