简体   繁体   中英

Extracting values from a dictionary in Python

Apologies for the potentially noobish question, I am stuck. I want to get some values to print out from from a dictionary within a list, within another dictionary called 'match'. The dictionary looks as below, as you can see it's a bit of a minefield. The dictionary profiles a golf betting market on Betfair between two players, 'Rose' and 'Garth Mulroy'. It is these two strings I want to extract. Any help greatly appreciated!

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

My attempt:

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

Produces the error:

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

If your original dictionary is called original_dict , original_dict[runners] gives the list of runners.

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

That was pretty tough to parse through though, and you probably want to organize your data in an easier to follow fashion. In any case, in the future please post more code to allow us to better understand your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM