0

I would like to get the index of the following key, value pair:

Key => [CorrectionHistory][Key] Value => 456

{'CorrectionHistory': [{'key': 123, 'CorrectionsAll': [{'CorrChngDesc': 'Discount Line Changed'}, {'CorrChngDesc': 'Commodity Line Changed'}]}, {'key': 456, 'CorrectionsAll': [{'CorrChngDesc': 'AC Added/Modified'}, {'CorrChngDesc': 'CMDY Added/Modified'}]}, {'key': 789, 'CorrectionsAll': [{'CorrChngDesc': 'AC Added/Modified'}]}}

Can someone please throw some light on this?

1
  • can you show us your desired output Commented Mar 15, 2019 at 11:37

2 Answers 2

3

I will assume that you have only the CorrectionHistory key as this is your example. In my example the function i wrote is very simple, just to prove is gets the job you mentioned done, but it can be easily generalized:

a = {
        'CorrectionHistory': [
            {'key': 123, 'CorrectionsAll': [{'CorrChngDesc': 'Discount Line Changed'}, {'CorrChngDesc': 'Commodity Line Changed'}]},
            {'key': 456, 'CorrectionsAll': [{'CorrChngDesc': 'AC Added/Modified'}, {'CorrChngDesc': 'CMDY Added/Modified'}]},
            {'key': 789, 'CorrectionsAll': [{'CorrChngDesc': 'AC Added/Modified'}]}
        ]
    }


def get_index_for_key(key):
    for index, item in enumerate(a['CorrectionHistory']):
        if item['key'] == key:
            return index
    return None


print(get_index_for_key(456))

Result: 1 the index you are looking for

Please let me know if this is what you are looking for.

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

Comments

0

Also one liner:

data = {'CorrectionHistory': [{'key': 123, 'CorrectionsAll': [{'CorrChngDesc': 'Discount Line Changed'}, {'CorrChngDesc': 'Commodity Line Changed'}]}, {'key': 456, 'CorrectionsAll': [{'CorrChngDesc': 'AC Added/Modified'}, {'CorrChngDesc': 'CMDY Added/Modified'}]}, {'key': 789, 'CorrectionsAll': [{'CorrChngDesc': 'AC Added/Modified'}]}]}

index = [i for i, x in enumerate(data['CorrectionHistory']) if x['key'] == 456][0]

Output:

1

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.