0

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.

2
  • Do you want its position only? Commented Mar 10, 2021 at 11:19
  • Yes, only the position Commented Mar 10, 2021 at 11:30

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.