Looping on a list in json

Sayth Renshaw flebber.crue at gmail.com
Sat Nov 4 20:40:29 EDT 2017


> I'd just keep the interesting runners, along with their race numbers, in a 
> dict. The enumerate function is handy here. Something like (untested):
> 
>   runner_lists = {}
>   for n, item in enumerate(result):
>     if this one is interested/not-filtered:
>       runner_lists[n] = result["RacingFormGuide"]["Event"]["Runners"]
> 
> and just return runner_lists. That way you know what the race numbers were for 
> each list of runners.
> 

> 
> Cheers,
> Cameron Simpson 

The main issue is that enumerate doesn't enumerate on the lists when trying to filter.

result = meeting_id["Races"]

so yes enumerating this works, showing just printing n and item.

runner_lists = {}
    for n, item in enumerate(result):
        # if this one is interested / not -filtered:
        print(n, item)

0 {'FeatureRaceBonusActive': 'Disabled', 'FixedPriceSummary': {'FixedPrices': [{'SportId': 8, 'LeagueId': 102, 'MeetingId': 1218, 'MainEventId': 650350, 'SubEventId': 3601361, 'Status': 'F', 'StatusDescription': 'FINALISED', 'BetTypeName': 'Win', 'EnablePlaceBetting': True}]}, 'RacingFormGuide': {'Copyright': .....

and so on it goes through the 7 items in this file.

but including 

runner_lists = {}
    for n, item in enumerate(result):
        # if this one is interested / not -filtered:
        print(n, item)
        runner_lists[n] = result["RacingFormGuide"]["Event"]["Runners"]

## Produces

Traceback (most recent call last):
dict_keys(['RaceDay', 'ErrorInfo', 'Success'])
  File "/home/sayth/PycharmProjects/ubet_api_mongo/parse_json.py", line 31, in <module>
    runner_lists[n] = result["RacingFormGuide"]["Event"]["Runners"]
TypeError: list indices must be integers or slices, not str


Cheers

Sayth



More information about the Python-list mailing list