To sort a list of dictionaries, use a methodcaller
with the key on which to sort; you want to sort the results list, not the contained dictionaries. Moreover, some of the entries do not have a year, and that could lead to errors:
from operator import methodcaller
for row in sorted(json_object['results'], key=methodcaller('get', 'year', None)):
# process the row dictionary
The methodcaller
definition will basically do a entry.get('year', None)
for each entry in json_object['results']
, giving the sorted
method the value to sort on.
You should not use readlines()
to read your JSON response, it'll mis-interpret newlines. Let the json
library do the reading instead (note the .load()
, no s
at the end):
response = urllib2.urlopen(request)
json_object = json.load(response)