-2

I have dictionary which is below

{
    "id": "98992",
    "data": [
        {
            "app": "Market",
            "hash": "ajlfdfd",
            "nTime": "2021-02-24 16:03:29.149638"
        },
        {
            "app": "Market",
            "hash": "dfds560",
            "nTime": "2021-02-25 05:10:09.828576"
        },
        {
            "app": "Market",
            "hash": "dfdsfds73",
            "nTime": "2021-02-23 15:52:51.954543"
        }
       
    ]
}

You can see second is dictionary has to come, Latest has to come first

My expect out is same dictionary with Latest time at top

My psedo code is below

def test(mydict):
    for key in sorted(mydict):
       return (nTime, mydict['nTime'])

NB: I don't want to use Pandas

Nons
  • 207
  • 1
  • 9
  • The `sorted` function in python allows to sort something according to a values for examples `sorted(mydict['data'], key=lambda d: d['nTime'])` will sorted mydict['data'] according to the `'nTime'` value. Also you can use the [datetime.date.fromtimestamp](https://docs.python.org/3/library/datetime.html#datetime.date.fromtimestamp) to convert your date string into a python object that be compared. – ygorg Mar 01 '21 at 14:01
  • "*NB: I don't want to use Pandas*" Can you expand on the reason for this seemingly arbitrary requirement...? I'm not sure you'd *have* to per se, but what if it's the easiest/fastest/most reliable method? – esqew Mar 01 '21 at 14:01
  • Does this answer your question? [How do I sort a list of dictionaries by a value of the dictionary?](https://stackoverflow.com/questions/72899/how-do-i-sort-a-list-of-dictionaries-by-a-value-of-the-dictionary) – Pierre D Mar 01 '21 at 14:05

1 Answers1

2

If your data is stored in variable called data you can use this:

data['data'] = sorted(data['data'], key=lambda x: x['nTime'], reverse=True)
zipa
  • 27,316
  • 6
  • 40
  • 58