json.dump() and sorted() dict
来源:互联网 发布:手机音乐软件 编辑:程序博客网 时间:2024/06/05 16:39
json.dump() and sorted() dict
Ref:
http://www.cnblogs.com/BeginMan/p/3193081.html
http://www.cnblogs.com/BeginMan/p/3178103.html
json.dump() returns an encoded string based on given data.
It transforms the type from tuple to list.
import json dict1 = [{'a': 'A', 'b': 123, 'c':(2, 4)}]encoded = json.dumps(dict1)print 'Original dict:', dict1print 'Encoded:', encoded
Output:
Original dict: [{'a': 'A', 'c': (2, 4), 'b': 123}]
Encoded: [{"a": "A", "c": [2, 4], "b": 123}]
Here you can see the value of key 'c' becomes a list.
************************************************************
sorted() can be used to sort by key or value in a dict. If you want to use reversed order, you should explicitly pass the argument.
import json data1 = {'b':789,'c':456,'a':123} d1 = json.dumps(data1,sort_keys=True) print 'Encoded unsorted dict:', d1print 'Original dict unsorted:', data1print 'Original dict SORTED BY VALUE:', sorted(data1.iteritems(), key=(lambda d:d[1]), reverse=True)
Output:
Encoded unsorted dict: {"a": 123, "b": 789, "c": 456}
Original dict unsorted: {'a': 123, 'c': 456, 'b': 789}
Original dict SORTED BY VALUE: [('a', 123), ('c', 456), ('b', 789)]
key=(lambda d:d[0])
means to sort by key.
sorted(data1.iteritems(), key=(lambda d:d[0]), reverse=True)
means to sort by key reversely.
Notes:
data1 is iterable, while d1 is a string which is not iterable.
Make sure you are not using 'reversed' which is a function instead of an argument.
revsd = reversed([1,2,3,4,5]) print 'reversed object:', revsdprint 'reversed list:', list(revsd)
Output:
reversed object: <listreverseiterator object at 0x0252E6D0>
reversed list: [5, 4, 3, 2, 1]
- json.dump() and sorted() dict
- dict to json And json to dict
- 简单代码,测试一下json.dump and json.loads
- python dict sorted
- python dict sorted 排序
- python dict sorted 排序
- python dict sorted 排序
- python dict sorted 排序
- json.dump
- json dict python base64
- json to dict
- sort list and dict
- list and dict
- Python-dict AND set
- python 中Dict 转 Json
- python dict与json转换
- python json 转 dict , list
- python dict json读写文件
- A500的dial过程选择phone
- 线段树
- bzoj2521: [Shoi2010]最小生成树 最小割
- POJ 1904 King's Quest(强连通)
- 【JAVA】【NIO】8、Java NIO FileChannel
- json.dump() and sorted() dict
- cocos2dx 工程运行时 发生访问冲突 有可能是消息未移除的原因
- 高仿微信5.2.1主界面架构 包含消息通知
- [Help] Syncfusion.XlsIO componet 's bug in open "xlsx"file.
- poj1189 简单dp
- cocos2dx3.3开发FlappyBird总结八:载入场景LoadingScene
- 如何查看linux发行版版本信息
- iGrimace OpenSSH的安装
- ScheduledExecutorService 根据条件终止调度任务