import requests
from operator import itemgetter

#Make an API call and store the response
url='https://hacker-news.firebaseio.com/v0/topstories.json'
r=requests.get(url)
print("Status Code:", r.status_code)

#Process information about each submission
submission_ids=r.json() #return a list
submission_dicts=[]
for submission_id in submission_ids[:30]:
	#Make a separate API call for each submission
	url=('https://hacker-news.firebaseio.com/v0/item/'+str(submission_id)+'.json')
	submission_r=requests.get(url)
	print(submission_r.status_code)
	response_dict=submission_r.json()

	submission_dict={
		'title':response_dict['title'],
		'link': 'http://news.ycombinator.com/item?=id=' + str(submission_id),
		#When not sure if a key exists in a dictionary, use the dict.get() method,
		#which returns the value associated with the given key if it exists or the value you provide if the key doesn't exist (0 in this example)
		'comments':response_dict.get('descendants',0)
	}
	submission_dicts.append(submission_dict)

'''
itemgetter() from operator
We pass this function the key 'comments', and it pulls the value associated with that key from each dictionary in the list
sorted() use the value from itemgetter() to sort the list
reverse=True, descending order
'''
submission_dicts=sorted(submission_dicts,key=itemgetter('comments'),reverse=True)

for submission_dict in submission_dicts:
	print('\nTitle:', submission_dict['title'])
	print('Discussion link:', submission_dict['link'])
	print('Comments:', submission_dict['comments'])
