Skip to content
Advertisement

Python – Find and get the position of element in array

I have a json file like below

{

    "sample": 100,
    "columns": [{
            "name": "col1",
            "value": 11
        },
        {
            "name": "col2",
            "value": 210
        }, 
                ..... 
        {
            "name": "col10",
            "value": 20
        }
    ]
}

I need to find the position of name: col10 in the columns array.

Advertisement

Answer

something like the below

data = {

    "sample": 100,
    "columns": [{
        "name": "col1",
        "value": 11
    },
        {
            "name": "col2",
            "value": 210
        },
        {
            "name": "col10",
            "value": 20
        }
    ]
}

col_name = 'col2'
for idx, entry in enumerate(data['columns']):
    if entry['name'] == col_name:
        print(f'index of {col_name} is {idx}')
        # assuming it can be found once - break
        break

output

index of col2 is 1
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement