如何按键的值和键值的值对字典列表进行排序?

时间:2016-10-06 21:30:38

标签: python list sorting dictionary

{
    "states": [
        {
            "timestamp": {
                "double": 968628281.0
            },
            "sensorSerialNumber": 13020235
        },
        {
            "timestamp": {
                "double": 964069109.0
            },
            "sensorSerialNumber": 13020203
        },
        {
            "timestamp": {
                "double": 9641066.0
            },
            "sensorSerialNumber": 30785
        }
    ]
}

有没有办法按" sensorSerialNumber"排序这个词典列表?并且通过这个数字在" timestamp"的值内; (9.68628281E8),

"timestamp":{"double":9.68628281E8}

使用内置函数(排序

from operator import itemgetter
newlist = sorted(list_to_be_sorted, key=itemgetter('name'))

但是,我的问题与其他问题略有不同。如果字典中没有字典,我只需要将第二个字符串添加到内置函数中,如:

from operator import itemgetter
newlist = sorted(list_to_be_sorted, key=itemgetter('name', 'age'))

1 个答案:

答案 0 :(得分:2)

key可以是任何可调用的,它依次传递给list_to_be_sorted中的每个元素。所以lambda适合这里:

newlist = sorted(
    data['states'],
    key=lambda i: (i['sensorSerialNumber'], i['timestamp']['double']))

因此lambda返回'sensorSerialNumber'键的值作为元组的第一个元素,以及'double'键的值来自'timestamp'键的字典值。 / p>

演示:

>>> 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}}]

该演示没有那么有意义,因为没有相同的序列号来包含时间戳值以产生影响。