Sort Json data in list according to timestamp

廉价感情. 提交于 2019-12-11 16:58:40

问题


I am loading data(20 elements) to another file on load...here I want to sort these 20 elements according to timestamp I am using in list element.

import json
from collections import OrderedDict
import datetime
import os

if os.path.exists("qwerty.json"):
    record = json.load(open("qwerty.json", "r"), object_pairs_hook=OrderedDict)
else:
    record = OrderedDict({})

fo = open("foo.txt", "wb")
abc = list(record.items())[:20] 
print(abc)

command = ""
while command != 'exit':
    command = input('Enter a command(options: create,read,save): ')
    if command == "create":
        name = input('Enter name of the Student:')
        p = input('Student ID: ')
        a = input('Class: ')
        n = input('Marks: ')
        time = datetime.datetime.now().isoformat()

        record[name] = {'Student ID:': p, 'Class:': a, 'Marks': n, 'time': time }

    elif command == 'read':
        z = json.load(open("qwerty.json", "r"), object_pairs_hook=OrderedDict)
        print(z)

    elif command == 'save':
        json.dump(record, open('qwerty.json', "w"))

fo.close()

回答1:


Trivia:

Since you're using an OrderedDict - your records are already sorted by timestamp (to be honest - they're not, but recordses order is preserved).

The only unexpected behaviour with your code - when you "create" (overwrite) existed one student in line:

record[name] = {'Student ID:': p, 'Class:': a, 'Marks': n, 'time': time }

And if name in record: already - order is broken, so your idea about sorting isn't a meaningless, but I think, that it's better and more rational to just be sure of the recordses order, than sort records each time.

Workaround:

Square brackets after variable name means that this object is subscriptable (for e.g. tuple, list, dict, string and many more). Subscriptable means that this object at least implements the __getitem__() method (and __setitem__() in your case).

First method handles case, when you're trying to pull something from subscriptable object (by index/key/anything) and the second one - when you're trying to overwrite something.

And I suggest to implement such a feature with custom class:

class OrderedTimeDict(OrderedDict):
    def __setitem__(self, key, value):
        if key in self:
            # if key is already exist - move it to the end
            self.move_to_end(key)
        # standard behaviour
        OrderedDict.__setitem__(self, key, value)

and in your code just use this ordered dictionary instead of base ordered!

Conclusion:

Pros: No need to sort things, because we keep desired order.

Cons: If you're already has "unordered" data - you need to sort it once.

To sort ordered dict by time stamp you can use this function:

def sort_by_timestamp(dict):
    return OrderedDict(sorted(dict.items(), key=lambda get_time_stamp: get_time_stamp[1]['time']))

References:

  • In Python, what does it mean if an object is subscriptable or not?
  • OrderedDict Examples and Recipes


来源:https://stackoverflow.com/questions/44879392/sort-json-data-in-list-according-to-timestamp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!