Python executes “len” function outside of if statement but not inside

I am somewhat new to python. I’m writing a small script to use our tools api to help do some network mapping and discovery in our environment. The script is just about done but I’ve hit a weird situation where I cannot get a function to return anything after going through an if statement.

x = len(info['resources'][i]['addresses'])
if 'ip' in info['resources'][i]['addresses']:
    x = len(info['resources'][i]['addresses'])
    for j in range(0, x):
         ip.append(info['resources'][i]['addresses'][j]['ip'])

in this code I need to use the len(info['resources'][i]['addresses'] in the for loop to accurately pull the ips. The first function call before the if statement will return the correct number, but the second one (yes, I’ve verified that the if statement is triggering) does not work. Doesn’t matter if it is placed like that or if placed in the range(0, …) statement. Is there something that I’m just not seeing or something that is unique to python that won’t let that trigger?

Sample of the json I’m going through:

{
    "resources": [
        {
            "addresses": [
                {
                    "ip": "172.16.x.xx",
                    "mac": "00:0C:29:xx:xx:xx"
                }
            ],

Answer

You’re not testing if ip is in the dictionary, you’re testing whether ip is in the list. Since the list contains dictionaries, they’ll never be equal to a string.

The if statement should be inside the loop so you can test the specific element.

for addr in info['resources'][i]['addresses']:
    if 'ip' in addr:
        ip.append(addr['ip'])