1

I have a list of two dictionaries in Python

list = [{'id' : 'ewsfsdf', 
           '_source' : 
                      {'timestamp':'2018-08-08T20:56:01', 
                       'bytes':'43534534'}},
         {'id' : 'ewsfsdz', 
           '_source' : 
                      {'timestamp':'2018-08-08T20:57:01', 
                       'bytes':'4354343534'}}]

I would like to sort the list element by the timestamp in the 2nd depth dictionary. I looked up many other examples of python but could not find a suitable solution to order list element by a dictionary element of a dictionary element in a list.

Can you give me a clue?

davidism
  • 121,510
  • 29
  • 395
  • 339

5 Answers5

5
import datetime
l = [{'id' : 'ewsfsdf', 
           '_source' : 
                      {'timestamp':'2018-08-08T20:56:01', 
                       'bytes':'43534534'}},
         {'id' : 'ewsfsdz', 
           '_source' : 
                      {'timestamp':'2018-08-08T20:57:01', 
                       'bytes':'4354343534'}}]

print( sorted(l, key=lambda k: datetime.datetime.strptime(k['_source']["timestamp"], "%Y-%m-%dT%H:%M:%S")) )

or

print(sorted(l, key=lambda k: k['_source']['timestamp']))

Output:

[{'id': 'ewsfsdf', '_source': {'timestamp': '2018-08-08T20:56:01', 'bytes': '43534534'}}, {'id': 'ewsfsdz', '_source': {'timestamp': '2018-08-08T20:57:01', 'bytes': '4354343534'}}]
  • You can use lambda in key
  • Use datetime.datetime.strptime(k['_source']["timestamp"], "%Y-%m-%dT%H:%M:%S") to convert string to datetime object
Rakesh
  • 81,458
  • 17
  • 76
  • 113
1

You can do:

print(sorted(list, key=lambda d: d['_source']['timestamp']))

Depending on how you want to sort by timestamp, you may need to parse the timestamp to another format that's comparable time-wise and not just lexicographical order.

Kent Munthe Caspersen
  • 5,918
  • 1
  • 35
  • 34
1

Another solution is to use list method sort and dparser

from dateutil.parser import dparser
l.sort(key=lambda x: dparser.parse(x['_source']['timestamp']))

Notice that this will return nothing and sort your list inplace

rafaelc
  • 57,686
  • 15
  • 58
  • 82
0

Use dateutil package to parse datetime and sort it based on that. You can install dateutil package by doing pip install python-dateutil

from dateutil import parser
sorted(lst, key=lambda x: parser.parse(x['_source']["timestamp"]))
# [{'id': 'ewsfsdf', '_source': {'timestamp': '2018-08-08T20:56:01', 'bytes': '43534534'}}, {'id': 'ewsfsdz', '_source': {'timestamp': '2018-08-08T20:57:01', 'bytes': '4354343534'}}]
Sunitha
  • 11,777
  • 2
  • 20
  • 23
0

I'm not sure how you want to sort the timestamp (from earliest to latest or latest to earliest) but here's how you could get into the second depth:

list[0]['_source']['timestamp']

If you want to cycle through the whole list, simply get the length of the list and cycle through a for loop (make sure not to overflow the list by going out of range with the index).

I hope this helps!