Sort Json Data In List According To Timestamp
Solution 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:
classOrderedTimeDict(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:
defsort_by_timestamp(dict):
return OrderedDict(sorted(dict.items(), key=lambda get_time_stamp: get_time_stamp[1]['time']))
Post a Comment for "Sort Json Data In List According To Timestamp"