2011-11-11 87 views
1

我有類型的字典字典:如何在列表中向後循環一個字典列表,直到找到特定的鍵值爲止?

for i in results[2]: 
    print i 

Recurring: {'p_pnref': 'E78P2DFEA7E3', 'p_result': '12'} 
Recurring: {'p_pnref': 'E78P2E93B933', 'p_result': '0'} 
Recurring: {'p_pnref': 'E35P0A5578D3', 'p_result': '12'} 
Recurring: {'p_pnref': 'E24P0AA506C3', 'p_result': '24'} 
Recurring: {'p_pnref': 'E25P0AFF2C43', 'p_result': '24'} 
Recurring: {'p_pnref': 'E34P0B4909A3', 'p_result': '24'} 

林感興趣的p_result值。我可以很容易地抓住最後條目與list(results[2])[-1].p_result但我想要去的是,通過列表循環,直到我着陸在入口p_result == 0。在這個例子中,它將是第二行(p_pnref == E78P2E93B933)。

我怎樣才能做到這一點?如果我可以迭代負指數,我想我可以找出其餘的,但我不知道如何做到這一點。

假設這些是定期付款和0 == successful payment,我試圖抓住「最近的成功交易」。

+0

如果這不是一個小的或快速正骯髒的項目較多,這類數據可能更適合於數據庫。 SQLite和Python很好地結合,佔地面積小,速度非常快 - 並且可以用來完成這些查詢 – Robert

回答

4

我覺得reversed是你在找什麼:

records = [ 
    {'p_pnref': 'E78P2DFEA7E3', 'p_result': '12'}, 
    {'p_pnref': 'E78P2E93B933', 'p_result': '0'}, 
    {'p_pnref': 'E35P0A5578D3', 'p_result': '12'}, 
    {'p_pnref': 'E24P0AA506C3', 'p_result': '24'}, 
    {'p_pnref': 'E25P0AFF2C43', 'p_result': '24'}, 
    {'p_pnref': 'E34P0B4909A3', 'p_result': '24'}, 
] 

for record in reversed(records): 
    if record['p_result'] == '0': 
     print record['p_pnref'] 
     break 
+0

holllly廢話。發佈問題後我自己寫了這個。就像T.尼斯一樣。 – Flowpoke

0

也許你想:

for i in reversed(results[2]): 
    if i["p_result"] == "0": 
     do_stuff(i) 
相關問題