Reputation: 11
{
"states": [
{
"timestamp": {
"double": 968628281.0
},
"sensorSerialNumber": 13020235
},
{
"timestamp": {
"double": 964069109.0
},
"sensorSerialNumber": 13020203
},
{
"timestamp": {
"double": 9641066.0
},
"sensorSerialNumber": 30785
}
]
}
Is there a way to sort this list of dictionaries by "sensorSerialNumber" and by this number inside the value of "timestamp" (9.68628281E8),
"timestamp":{"double":9.68628281E8}
using the built-in function(sorted)
from operator import itemgetter
newlist = sorted(list_to_be_sorted, key=itemgetter('name'))
However, my question is slightly different from other questions. If there wasn't a dictionary inside the dictionary I would just need to add the string of the second key to the built-in function, like:
from operator import itemgetter
newlist = sorted(list_to_be_sorted, key=itemgetter('name', 'age'))
Upvotes: 1
Views: 62
Reputation: 1121406
key
can be any callable, it is passed each element in the list_to_be_sorted
in turn. So a lambda
would fit here:
newlist = sorted(
data['states'],
key=lambda i: (i['sensorSerialNumber'], i['timestamp']['double']))
So the lambda returns the value for the 'sensorSerialNumber'
key as the first element of a tuple, and the value for the 'double'
key from the dictionary value for the 'timestamp'
key.
Demo:
>>> data = {"states" :
... [{"timestamp":{"double":9.68628281E8},"sensorSerialNumber":13020235},
... {"timestamp":{"double":9.64069109E8},"sensorSerialNumber":13020203},
... {"timestamp":{"double":9641066.0},"sensorSerialNumber":30785}]
... }
>>> sorted(data['states'], key=lambda i: (i['sensorSerialNumber'], i['timestamp']['double']))
[{'timestamp': {'double': 9641066.0}, 'sensorSerialNumber': 30785}, {'timestamp': {'double': 964069109.0}, 'sensorSerialNumber': 13020203}, {'timestamp': {'double': 968628281.0}, 'sensorSerialNumber': 13020235}]
>>> from pprint import pprint
>>> pprint(_)
[{'sensorSerialNumber': 30785, 'timestamp': {'double': 9641066.0}},
{'sensorSerialNumber': 13020203, 'timestamp': {'double': 964069109.0}},
{'sensorSerialNumber': 13020235, 'timestamp': {'double': 968628281.0}}]
The demo is not that meaningful, as there are no equal serial numbers for the inclusion of the timestamp value to make a difference.
Upvotes: 2