Python3,订购一个复杂的字典

时间:2017-05-01 07:46:54

标签: python dictionary

我有一个复杂的Python字典,它存储以下值: MAC ADDRESS,RSSI和TIMESTAMP:

beacons_detected = {
    '55:c1:9a:41:4c:b9': ['-78', '1493580469'],
    '9c:20:7b:e0:6c:41': ['-74', '1493622425'],
    '5e:30:e7:12:97:64': ['-79', '1493587968']
}

我想根据时间戳订购该列表......有关如何实现这一目标的任何想法吗?

2 个答案:

答案 0 :(得分:4)

将字典从最小到最大排序:

>>> sorted(beacons_detected.items(), key=lambda x: x[1][1])
[('55:c1:9a:41:4c:b9', ['-78', '1493580469']), ('5e:30:e7:12:97:64', ['-79', '1493587968']), ('9c:20:7b:e0:6c:41', ['-74', '1493622425'])]

将字典从大到小排序:

>>> sorted(beacons_detected.items(), key=lambda x: x[1][1], reverse=True)
[('9c:20:7b:e0:6c:41', ['-74', '1493622425']), ('5e:30:e7:12:97:64', ['-79', '1493587968']), ('55:c1:9a:41:4c:b9', ['-78', '1493580469'])]

答案 1 :(得分:0)

如果您需要排序字典,请使用OrderedDict中的collections

>>> ordered = OrderedDict(sorted(beacons_detected.items(), key=lambda x: x[1][1]))
OrderedDict([('55:c1:9a:41:4c:b9', ['-78', '1493580469']),
             ('5e:30:e7:12:97:64', ['-79', '1493587968']),
             ('9c:20:7b:e0:6c:41', ['-74', '1493622425'])])

访问权限与dict相同:

>>> ordered['55:c1:9a:41:4c:b9']
['-78', '1493580469']