TheDataGuy
TheDataGuy

Reputation: 3098

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.

Upvotes: 0

Views: 71

Answers (3)

ApplePie
ApplePie

Reputation: 8942

A simple solution using dropwhile from itertools. This loops through an iterable until the function passed to it returns false. It then returns a generator containing every item from that point onwards.

from itertools import dropwhile

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

def col10_not_found(index_dict_tuple):
    return index_dict_tuple[1]["name"] != "col10"

print(next(dropwhile(col10_not_found, enumerate(data["columns"])))[0])
# output: 2

Note that this will break if col10 is not found, this is merely an illustration of how to get to the desired result. The missing col10 could be handled by handling StopIteration, for example.

Upvotes: 1

balderman
balderman

Reputation: 23815

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

Upvotes: 0

gribvirus74
gribvirus74

Reputation: 765

You can do it with next and enumerate:

import json


with open('data.json') as f:
    columns = json.load(f)['columns']

try:
    position = next(
      idx for idx, col in enumerate(columns)
      if col['name'] == 'col10'
    )
except StopIteration:
    print('No such element')
else:
    print('Position:', position)

Upvotes: 0

Related Questions