根据时间戳对列表中的Json数据进行排序 [英] Sort Json data in list according to timestamp
问题描述
我正在加载数据(20个元素)到另一个加载的文件...在这里,我想根据我在list元素中使用的时间戳对这20个元素进行排序.
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()
推荐答案
琐事:
由于您使用的是OrderedDict
-您的记录已经按时间戳进行了排序(说实话-它们不是,但是保留了记录顺序).
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 }
并且if name in record:
已经-顺序被破坏了,所以您关于排序的想法并不是毫无意义,但是我认为,仅要确定记录的顺序比每次对记录进行排序会更好,更合理.
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.
方括号表示该对象是可下标的(例如,元组,列表,字典,字符串等). Subscriptable 表示此对象至少实现__getitem__()
方法(在您的情况下为__setitem__()
).
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).
当您尝试从 subscriptable 对象(通过索引/键/任何东西)中提取内容时,第一种方法处理情况;而当您尝试覆盖某些内容时,第二种方法处理情况.
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!
优点:无需排序,因为我们保持了所需的顺序.
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']))
参考文献:
- 在Python中,一个对象是否可以下标是什么意思?
- OrderedDict示例和食谱
- In Python, what does it mean if an object is subscriptable or not?
- OrderedDict Examples and Recipes
References:
这篇关于根据时间戳对列表中的Json数据进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!