我從API密鑰獲取json。 這是我的JSON:從詞典列表中獲取前5個值?
{'[{"count":27,"stem":"obama","term":"obama"},
{"count":20,"stem":"boehner","term":"boehner"},
{"count":4,"stem":"tax","term":"tax"},
{"count":3,"stem":"daley","term":"daley"},
{"count":3,"stem":"couldn","term":"couldn"},
{"count":2,"stem":"formul","term":"formulation"}
]' : ' '}
,我想從這個JSON獲得前5名的值。我把這個列出詞典:
def changetodict(data):
json_str = ast.literal_eval(json.dumps(data))
#common = json.loads(json_str)
commonDict = dict(itertools.izip_longest(*[iter(json_str)] * 2,
fillvalue=""))
print commonDict
這是所有代碼:
import urllib2, mediacloud, json,itertools,ast
from collections import Counter
webUrl = urllib2.urlopen("https://api.mediacloud.org/api/v2/wc/list?q=obama+AND+media_id:1&stats=1&&fq=publish_date:%5B2012-04-01T00:00:00.000Z+TO+2012-04-01T00:00:00.000Z%5D&key= ")
def changetodict(data):
json_str = ast.literal_eval(json.dumps(data))
#common = json.loads(json_str)
commonDict = dict(itertools.izip_longest(*[iter(json_str)] * 2, fillvalue=""))
print commonDict
most_common_imdb_value = Counter(b['key'] for b in commonDict).most_common(1)[0]
if(webUrl.getcode()== 200):
data = webUrl.readlines()
changetodict(data)
else:
print "error"
什麼我需要改變,使其工作?
可以顯示您所希望輸出的例子嗎? –
{「count」:27,「stem」:「obama」,「term」:「obama」},{「count」:20,「stem」:「boehner」,「term」:「boehner」}, 「count」:4,「stem」:「稅」,「term」:「稅」} @Ni。 – adi
我只看到3件物品,你是說前三名? –