python按值排序json列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26924812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python sort list of json by value
提问by icycandy
I have a file consists of JSON, each a line, and want to sort the file by update_time reversed.
我有一个由 JSON 组成的文件,每行一行,并希望按反向更新时间对文件进行排序。
sample JSON file:
示例 JSON 文件:
{ "page": { "url": "url1", "update_time": "1415387875"}, "other_key": {} }
{ "page": { "url": "url2", "update_time": "1415381963"}, "other_key": {} }
{ "page": { "url": "url3", "update_time": "1415384938"}, "other_key": {} }
want output:
想要输出:
{ "page": { "url": "url1", "update_time": "1415387875"}, "other_key": {} }
{ "page": { "url": "url3", "update_time": "1415384938"}, "other_key": {} }
{ "page": { "url": "url2", "update_time": "1415381963"}, "other_key": {} }
my code:
我的代码:
#!/bin/env python
#coding: utf8
import sys
import os
import json
import operator
#load json from file
lines = []
while True:
line = sys.stdin.readline()
if not line: break
line = line.strip()
json_obj = json.loads(line)
lines.append(json_obj)
#sort json
lines = sorted(lines, key=lambda k: k['page']['update_time'], reverse=True)
#output result
for line in lines:
print line
The code works fine with sample JSON file, but if a JSON has no 'update_time', it will raise KeyError exception. Are there non-exception ways to do this?
该代码适用于示例 JSON 文件,但如果 JSON 没有“update_time”,则会引发 KeyError 异常。有没有非例外的方法来做到这一点?
采纳答案by Ferdinand Beyer
Write a function that uses try...exceptto handle the KeyError, then use this as the keyargument instead of your lambda.
编写一个try...except用于处理 的函数KeyError,然后使用 this 作为key参数而不是 lambda。
def extract_time(json):
try:
# Also convert to int since update_time will be string. When comparing
# strings, "10" is smaller than "2".
return int(json['page']['update_time'])
except KeyError:
return 0
# lines.sort() is more efficient than lines = lines.sorted()
lines.sort(key=extract_time, reverse=True)
回答by alecxe
You can use dict.get()with a default value:
您可以使用dict.get()默认值:
lines = sorted(lines, key=lambda k: k['page'].get('update_time', 0), reverse=True)
Example:
例子:
>>> lines = [
... {"page": {"url": "url1", "update_time": "1415387875"}, "other_key": {}},
... {"page": {"url": "url2", "update_time": "1415381963"}, "other_key": {}},
... {"page": {"url": "url3", "update_time": "1415384938"}, "other_key": {}},
... {"page": {"url": "url4"}, "other_key": {}},
... {"page": {"url": "url5"}, "other_key": {}}
... ]
>>> lines = sorted(lines, key=lambda k: k['page'].get('update_time', 0), reverse=True)
>>> for line in lines:
... print line
...
{'other_key': {}, 'page': {'url': 'url1', 'update_time': '1415387875'}}
{'other_key': {}, 'page': {'url': 'url3', 'update_time': '1415384938'}}
{'other_key': {}, 'page': {'url': 'url2', 'update_time': '1415381963'}}
{'other_key': {}, 'page': {'url': 'url4'}}
{'other_key': {}, 'page': {'url': 'url5'}}
Though, I would still follow the EAFPprinciplethat Ferdinand suggested - this way you would also handle cases when pagekey is also missing. Much easier to let it fail and handle it than checking all sorts of corner cases.
尽管如此,我仍然会遵循Ferdinand 建议的EAFP原则- 这样你也可以处理page密钥丢失的情况。让它失败并处理它比检查各种极端情况要容易得多。
回答by gurel_kaynak
# sort json
lines = sorted(lines, key=lambda k: k['page'].get('update_time', 0), reverse=True)
回答by Mrinal
def get_sortest_key(a: dict, o: dict):
v = None
k = None
for key, value in a.items():
if v is None:
v = value
k = key
continue
if v > value:
v = value
k = key
o.update({k: v})
a.pop(k)
if a:
get_sortest_key(a, o)
else:
return
def call(o):
a = {'a': 9, 'b': 1, 'c': 3, 'k': 3, 'l': -1, 's': 100}
z = get_sortest_key(a, o)
print(o)
o={}
call(o)

