0

I am trying to parse...k[1] element in the dictionary(which is of time stamp and I have to sort according to those only) but every time on insert the order of element gets changed...

import json
from collections import OrderedDict
import time
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")

x = list(record.items())[-20:];
#x = list(record.items())[:20];
x2 = sorted(x, key=lambda k: k[1]['time'], reverse=True)
print(x2)

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 = time.time()

        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"))
        command = 'exit'

fo.close()
  • 4
    please, reduce your code to just what's important to the question, and give a sample of what's on the `qwerty.json`file. – Ghilas BELHADJ Jul 03 '17 at 12:06
  • 2
    [This](https://stackoverflow.com/questions/44879392/sort-json-data-in-list-according-to-timestamp/44883857) one looks way too similar. – CommonSense Jul 03 '17 at 12:15
  • 2
    @CommonSense And [this](https://stackoverflow.com/questions/44875167/trying-to-implement-a-cache-on-load-of-this-file). By the way I ended up answering the question you linked in the comments of my answer. Help-vampire strikes again! – cs95 Jul 03 '17 at 12:17
  • @cᴏʟᴅsᴘᴇᴇᴅ where..? – ayush asthana Jul 03 '17 at 12:35
  • "_Dictionaries do not have an implicit ordering for versions of python below 3.6. You can use an OrderedDict for the inner dicts as well, if you wish._" – cs95 Jul 03 '17 at 12:36
  • Got it & thanks. @cᴏʟᴅsᴘᴇᴇᴅ – ayush asthana Jul 03 '17 at 14:26
  • 1
    Possible duplicate of [Sort Json data in list according to timestamp](https://stackoverflow.com/questions/44879392/sort-json-data-in-list-according-to-timestamp) – NotABlueWhale Jul 03 '17 at 14:50

0 Answers0