Python使用数组识别字典上的索引

时间:2019-03-15 11:34:59

标签: python arrays dictionary indexing key-value

我想获取以下键值对的索引:

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'}]}}

有人可以对此进行说明吗?

2 个答案:

答案 0 :(得分:3)

我将假设您只有CorrectionHistory键,因为这是您的示例。在我的示例中,我编写的函数非常简单,只是为了证明已完成您提到的工作,但是可以很容易地将其推广:

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))

结果:1您要查找的索引

请问这是您要寻找的东西。

答案 1 :(得分:0)

还有一个班轮:

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]

输出:

1