programing

값에 따른 json의 python 정렬 목록

iphone6s 2023. 3. 28. 21:19
반응형

값에 따른 json의 python 정렬 목록

JSON으로 구성된 파일을 가지고 있는데, 각각 한 줄씩 파일을 update_time reverse로 정렬하고 싶습니다.

샘플 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": {} }

출력 필요:

{ "page": { "url": "url1", "update_time": "1415387875"}, "other_key": {} }
{ "page": { "url": "url3", "update_time": "1415384938"}, "other_key": {} }
{ "page": { "url": "url2", "update_time": "1415381963"}, "other_key": {} }

내 코드:

#!/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

샘플 JSON 파일에서 코드는 정상적으로 동작하지만 JSON에 'update_time'이 없는 경우 KeyError 예외가 발생합니다.예외적인 방법이 있나요?

를 사용하는 함수를 작성합니다.try...except을 처리하다KeyError, 그 후, 이것을key당신의 람다 대신 논쟁을 하세요.

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)

를 디폴트값으로 사용할 수 있습니다.

lines = sorted(lines, key=lambda k: k['page'].get('update_time', 0), reverse=True)

예:

>>> 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'}}

하지만, 퍼디난드가 제안한 원칙을 따를 것입니다 - 이렇게 하면 당신도 사건을 처리할 수 있습니다.page키도 없습니다.모든 종류의 궁지에 몰린 사건들을 확인하는 것보다 실패하게 놔두고 처리하는 게 훨씬 쉽죠

# sort json
lines = sorted(lines, key=lambda k: k['page'].get('update_time', 0), reverse=True)
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)

언급URL : https://stackoverflow.com/questions/26924812/python-sort-list-of-json-by-value

반응형