2012-11-29 225 views
1

對於潛在的新手問題抱歉,我被卡住了。我想從列表中的字典中打印出一些值,並在另一個名爲'match'的字典中打印出來。字典看起來如下,你可以看到它是一個雷區。該詞典描述了兩名球員'Rose'和'Garth Mulroy'之間的必發高爾夫投注市場。這是我想要提取的這兩個字符串。任何幫助非常感謝!從Python中的字典中提取值

match = bot.get_market(matches[0]) 
from pprint import pprint 
pprint(match) 

{'bspMarket': 'false', 
'countryISO3': 'ZAF', 
'couponLinks': '', 
'discountAllowed': 'true', 
'eventTypeId': '3', 
'event_ids': ['3', '26909125', '26930851'], 
'interval': '0.0', 
'lastRefresh': '1354218248109', 
'licenceId': '1', 
'marketBaseRate': '5.0', 
'marketDescriptionHasDate': 'true', 
'marketDisplayTime': '2012-11-30T09:10:00.000Z', 
'marketId': '107625660', 
'marketStatus': 'ACTIVE', 
'marketSuspendTime': '2012-11-30T09:10:00.000Z', 
'marketTime': '2012-11-30T09:10:00.000Z', 
'marketType': 'O', 
'marketTypeVariant': 'D', 
'maxUnitValue': '0.0', 
'menuPath': '\\Group B\\Nedbank Challenge 2012\\2nd Round 2 Balls', 
'minUnitValue': '0.0', 
'name': 'Rose', 
'numberOfWinners': '1', 
'parentEventId': '26930851', 
'runners': [{'asian_line_id': '0', 
       'handicap': '0.0', 
       'name': 'Justin Rose', 
       'selection_id': '2078854'}, 
      {'asian_line_id': '0', 
       'handicap': '0.0', 
       'name': 'Garth Mulroy', 
       'selection_id': '2235937'}, 
      {'asian_line_id': '0', 
       'handicap': '0.0', 
       'name': 'Tie', 
       'selection_id': '39905'}], 
'runnersMayBeAdded': 'false', 
'timezone': 'RSA', 
'unit': ''} 

我嘗試:

match = bot.get_market(matches[0]) 
for runners in match: 
    print runners['name'] 

產生錯誤:

Traceback (most recent call last): 
    File "C:/Python27/bots/test.py", line 31, in <module> 
    print runners['name'] 
TypeError: string indices must be integers, not str 
+1

請問您是否可以減少/簡化您的輸入。 – alexvassel

+0

根據要求添加了我的嘗試 – RichieCunningham

+2

我已經修改了帖子以使用pprint來顯示數據 - 使其對所有人更具可讀性 –

回答

3

如果你原來的字典被稱爲original_dictoriginal_dict[runners]給跑步者的名單。

runner_list = original_dict["runners"] 
for runner in runner_list: 
    name_you_are_looking_for = runner["name"] 

這是非常艱難的,雖然通過解析,你可能想組織你的數據在一個更容易理解的方式。無論如何,將來請發佈更多代碼,以便我們更好地瞭解您的問題。

+0

謝謝,先生 – RichieCunningham