2014-01-11 36 views
-2

返回一個值,我想從以下字典返回「runnerName」:從多個值的字典鑰匙在python

{u'marketId': u'1.112422365', 
u'marketName': u'1m Mdn Stks', 
u'runners': [{u'handicap': 0.0, 
       u'runnerName': u'La Napoule', 
       u'selectionId': 8095372, 
       u'sortPriority': 1}, 
       {u'handicap': 0.0, 
       u'runnerName': u'Swivel', 
       u'selectionId': 701378, 
       u'sortPriority': 2}, 
       {u'handicap': 0.0, 
       u'runnerName': u'Deanos Devil', 
       u'selectionId': 8100420, 
       u'sortPriority': 3}, 
       {u'handicap': 0.0, 
       u'runnerName': u'Bishan Bedi', 
       u'selectionId': 8084336, 
       u'sortPriority': 4}, 
       {u'handicap': 0.0, 
       u'runnerName': u'In Seine', 
       u'selectionId': 8199415, 
       u'sortPriority': 5}, 
       {u'handicap': 0.0, 
       u'runnerName': u'Needs The Run', 
       u'selectionId': 8199416, 
       u'sortPriority': 6}, 
       {u'handicap': 0.0, 
       u'runnerName': u'Appellez Baileys', 
       u'selectionId': 8148513, 
       u'sortPriority': 7}, 
       {u'handicap': 0.0, 
       u'runnerName': u'Jessy Mae', 
       u'selectionId': 7652545, 
       u'sortPriority': 8}, 
       {u'handicap': 0.0, 
       u'runnerName': u'Redy To Rumble', 
       u'selectionId': 7366163, 
       u'sortPriority': 9}]} 

我已經嘗試了許多不同的方法,但無法弄清楚如何訪問值從具有多個值的密鑰開始。

+4

'[d [ 'runnerName']爲d ['亞軍']]' – falsetru

+0

您可能想與我們分享您嘗試的方式。我們將很樂意幫助你糾正它們:) – thefourtheye

+0

我嘗試了類似的東西,但保持,得到一個錯誤「TypeError:列表索引必須是整數,而不是str」訪問鍵值時,只有一個我可以做,有幾個抓住我了! –

回答

6
  1. 您可以像這樣使用列表理解從跑步者字典中檢索跑步者名稱。

    print [runner["runnerName"] for runner in runners_dict["runners"]] 
    
  2. 或者你可以在a_dict使用operator.itemgetter,這樣

    from operator import itemgetter 
    print map(itemgetter("runnerName"), runners_dict["runners"]) 
    

輸出

[u'La Napoule', u'Swivel', u'Deanos Devil', u'Bishan Bedi', u'In Seine', 
u'Needs The Run', u'Appellez Baileys', u'Jessy Mae', u'Redy To Rumble'] 
+0

非常感謝,我正在做一些與betfair api有關的事情,並且正在嘗試修改一些示例代碼來做我想做的事情,我認爲他們應該讓你去做文檔和示例,因爲你的方法比他們的方式要好得多完成了!再次感謝。 –

+0

@PadraicCunningham不客氣:)請考慮接受這個答案,如果它可以幫助你:) http://meta.stackexchange.com/a/5235/235416 – thefourtheye