打印按值排序的字典

时间:2016-05-10 23:07:37

标签: python dictionary

我正在尝试打印在此代码部分中按<!DOCTYPE html> <html> <head> <title>Device Properties Example</title> <script type="text/javascript" charset="utf-8" src="cordova.js"></script> <script type="text/javascript" charset="utf-8"> // Wait for device API libraries to load // document.addEventListener("deviceready", WatchCoarse, false); var watchID = null; // device APIs are available // function WatchCoarse() { // Get the most accurate position updates available on the // device. var options = { enableHighAccuracy: false }; watchID = navigator.geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: false }); } function WatchFine() { // Get the most accurate position updates available on the // device. var options = { enableHighAccuracy: true }; watchID = navigator.geolocation.watchPosition(onSuccess, onError, options); } // onSuccess Geolocation // function onSuccess(position) { var element = document.getElementById('geolocation'); element.innerHTML = 'Latitude: ' + position.coords.latitude + '<br />' + 'Longitude: ' + position.coords.longitude + '<br />' + '<hr />' + element.innerHTML; } // clear the watch that was started earlier // function clearWatch() { if (watchID != null) { navigator.geolocation.clearWatch(watchID); watchID = null; } } // onError Callback receives a PositionError object // function onError(error) { alert('code: ' + error.code + '\n' + 'message: ' + error.message + '\n'); } </script> </head> <body> <p id="geolocation">Watching geolocation...</p> <button onclick="clearWatch();">Clear Watch</button> <button onclick="WatchCoarse();">Watch Coarse</button> <button onclick="WatchFine()">Watch Fine</button> </body> </html> 排序的字典:

value

当我尝试运行程序时,我得到以下内容:

for key,value in frequency.items():
    output = key + ' : ' + str(value)

sorted_output = sorted(output.items(), key=operator.itemgetter(1))
print sorted_output

我该如何解决这个问题?

感谢。

1 个答案:

答案 0 :(得分:2)

您正在将键值对转换为字符串,而字符串没有.items()。所以它给出了错误。

试试这个:

from operator import itemgetter    
for k, v in sorted(frequency.items(), key=itemgetter(1)):
        print k, v