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

作者:abc15766228491 时间:2023-06-15 02:20:40 

如下所示:


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));

});

来源:https://blog.csdn.net/abc15766228491/article/details/78706049

标签:python,字典,json,排序
0
投稿

猜你喜欢

  • Mysql的慢SQL优化思路和规范详解

    2024-01-22 22:01:15
  • 详解Python import方法引入模块的实例

    2021-01-10 04:21:08
  • python信号量,条件变量和事件详解

    2021-10-06 18:14:23
  • 浅谈JavaScript中的parseInt()的妙用

    2024-04-19 10:47:52
  • keras:model.compile损失函数的用法

    2023-11-23 08:44:21
  • GO语言标准错误处理机制error用法实例

    2024-02-13 18:07:20
  • XMLHttpRequest的浏览器兼容代码写法

    2008-09-02 10:46:00
  • Python使用APScheduler实现定时任务过程解析

    2023-01-23 19:20:35
  • python二叉树遍历的实现方法

    2021-09-19 03:53:14
  • python安装pillow的三种方法

    2023-07-20 02:36:53
  • Python实现并行抓取整站40万条房价数据(可更换抓取城市)

    2021-09-24 10:56:43
  • 数据库中的SELECT语句逻辑执行顺序分析

    2024-01-28 06:32:18
  • Vue3中watch的使用详解

    2024-05-09 15:20:19
  • SQL 优化

    2024-01-16 10:50:40
  • Python使用Flask Migrate模块迁移数据库

    2023-08-10 09:17:30
  •  Python 匿名函数lambda 详情

    2022-07-30 12:37:39
  • Python使用 Beanstalkd 做异步任务处理的方法

    2021-01-06 18:18:19
  • SQL Server游标的介绍与使用

    2024-01-21 10:02:25
  • Python自定义sorted排序实现方法详解

    2022-08-03 05:40:02
  • python3使用diagrams绘制架构图的步骤

    2022-08-27 12:42:34
  • asp之家 网络编程 m.aspxhome.com