欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

python通过对字典的排序,对json字段进行排序的实例

时间:2021-01-28 10:23:21|栏目:Python代码|点击:

如下所示:

dic = dict()
dic['a'] = 1
dic['b'] = 2
dic['c'] = 3
print(dic.items())

import json
jsons = json.dumps(dic)
print(jsons)

结果:

dic is: dict_items([('c', 3), ('b', 2), ('a', 1)])
jsons: {"c": 3, "b": 2, "a": 1}

通过使用collecions,进行排序。collections是一个python的内建模块。

import collections
dic = collections.OrderedDict()
# dic = dict()
dic['a'] = 1
dic['b'] = 2
dic['c'] = 3
print("dic is:",dic.items())

import json
jsons = json.dumps(dic)
print("jsons:",jsons)

结果:

dic is: odict_items([('a', 1), ('b', 2), ('c', 3)])
jsons: {"a": 1, "b": 2, "c": 3}

补充拓展:对JSON集合 某个键进行升序/降序排列

我就废话不多说了,直接上代码吧

$(document).ready(function () { 
  //对json进行降序排序函数 
  var colId="age" 
  var desc = function(x,y) 
  { 
    return (x[colId] < y[colId]) ? 1 : -1 
  } 
  //对json进行升序排序函数 
  var asc = function(x,y) 
  { 
    return (x[colId] > y[colId]) ? 1 : -1 
  } 
  var arr2 = [ 
    {name:"kitty", age:12}, 
    {name:"sonny", age:9}, 
    {name:"jake", age:13}, 
    {name:"fun", age:24} 
  ]; 
  document.writeln("按age进行升序排序:<br>"); 
  arr2.sort(asc); //升序排序 
  document.writeln(JSON.stringify(arr2)); 
 
 
  document.writeln("<br>按age进行降序排序:<br>"); 
  arr2.sort(desc); //降序排序 
  document.writeln(JSON.stringify(arr2)); 
 
}); 

上一篇:Python基础教程之正则表达式基本语法以及re模块

栏    目:Python代码

下一篇:python脚本执行CMD命令并返回结果的例子

本文标题:python通过对字典的排序,对json字段进行排序的实例

本文地址:http://www.codeinn.net/misctech/52593.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有