I am currently getting JSON data from the discogs API (mp3 tag data) and wish to sort the results by the key's value. In this case I am trying to get data for a Guns n Roses song and the output has 1988 as the first one while the data actually has a record from 1987. How can I sort this data so that I can get to the sorted data by year (olderst to newest). The code below sorts by either key or value but thats not what I intended to get. Please help.
import json
import urllib2
request = urllib2.Request('http://api.discogs.com/database/search?sort=year&sort_order=asc&artist=%22Guns+N%27+Roses%22&track=%22Sweet+Child+O%27+Mine%22&format_exact=Album&type=master')
request.add_header('User-Agent','Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')
request.add_header('Content-Type','application/json')
response = urllib2.urlopen(request)
json_raw= response.readlines()
json_object = json.loads(json_raw[0])
for row in json_object['results']:
try:
from operator import itemgetter
for k, v in sorted(row.items(), key=itemgetter(0)):
print k, v
except KeyError:
pass
You could use list-comprehension and
sorted()
function for this:or :
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:The
methodcaller
definition will basically do aentry.get('year', None)
for each entry injson_object['results']
, giving thesorted
method the value to sort on.You should not use
readlines()
to read your JSON response, it'll mis-interpret newlines. Let thejson
library do the reading instead (note the.load()
, nos
at the end):