不为别的,只为做一个连自己都羡慕的人

python实现字典的排序

var dic = {c:4, a:2, d:3, b:1}; // 定义一个字典

console.log("输出最初的字典元素: "); 
for(var key in dic){
   console.log("key: " + key + " ,value: " + dic[key]);
}

console.log("字典元素按key值排序: ");
var res = Object.keys(dic).sort(); 
for(var key in res){
   console.log("key: " + res[key] + " ,value: " + dic[res[key]]);
}

console.log("字典元素按value值排序: ");
var res2 = Object.keys(dic).sort(function(a,b){ return dic[a]-dic[b]; });
for(var key in res2){
   console.log("key: " + res2[key] + " ,value: " + dic[res2[key]]);
}

 

posted @ 2022-07-07 15:01  升级打怪  阅读(165)  评论(0编辑  收藏  举报