How to sort a list of dictionaries by the value of a key and by the value of a value of a key?
<pre><code>{
    "states": [
        {
            "timestamp": {
                "double": 968628281.0
            },
            "sensorSerialNumber": 13020235
        },
        {
            "timestamp": {
                "double": 964069109.0
            },
            "sensorSerialNumber": 13020203
        },
        {
            "timestamp": {
                "double": 9641066.0
            },
            "sensorSerialNumber": 30785
        }
    ]
}
</code></pre>

<p>Is there a way to sort this list of dictionaries by "sensorSerialNumber" and by this number inside the value of "timestamp" (9.68628281E8),</p>

<pre><code>"timestamp":{"double":9.68628281E8}
</code></pre>

<p>using the built-in function(<em>sorted</em>)</p>

<pre><code>from operator import itemgetter
newlist = sorted(list_to_be_sorted, key=itemgetter('name'))
</code></pre>

<p>However, my question is <strong>slightly different from other questions</strong>. 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:</p>

<pre><code>from operator import itemgetter
newlist = sorted(list_to_be_sorted, key=itemgetter('name', 'age'))
</code></pre>

<p><code>key</code> can be any callable, it is passed each element in the <code>list_to_be_sorted</code> in turn. So a <code>lambda</code> would fit here:</p>

<pre><code>newlist = sorted(
    data['states'],
    key=lambda i: (i['sensorSerialNumber'], i['timestamp']['double']))
</code></pre>

<p>So the lambda returns the value for the <code>'sensorSerialNumber'</code> key as the first element of a tuple, and the value for the <code>'double'</code> key from the dictionary value for the <code>'timestamp'</code> key.</p>

<p>Demo:</p>

<pre><code>&gt;&gt;&gt; data = {"states" :
... [{"timestamp":{"double":9.68628281E8},"sensorSerialNumber":13020235},
... {"timestamp":{"double":9.64069109E8},"sensorSerialNumber":13020203},
... {"timestamp":{"double":9641066.0},"sensorSerialNumber":30785}]
... }
&gt;&gt;&gt; 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}]
&gt;&gt;&gt; from pprint import pprint
&gt;&gt;&gt; pprint(_)
[{'sensorSerialNumber': 30785, 'timestamp': {'double': 9641066.0}},
 {'sensorSerialNumber': 13020203, 'timestamp': {'double': 964069109.0}},
 {'sensorSerialNumber': 13020235, 'timestamp': {'double': 968628281.0}}]
</code></pre>

<p>The demo is not that meaningful, as there are no equal serial numbers for the inclusion of the timestamp value to make a difference.</p>

python list sorting dictionary