【问题标题】:Python3, ordering a complex dictPython3,订购一个复杂的字典
【发布时间】:2017-05-01 20:58:28
【问题描述】:

我有一个复杂的 Python 字典,它存储以下值: MAC 地址、RSSI 和时间戳:

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

我想根据时间戳订购该列表...您知道如何实现吗?

【问题讨论】:

  • 你期望什么输出?

标签: python dictionary


【解决方案1】:

将字典从小到大排序:

>>> 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'])]

【讨论】:

  • 理论上我们想要int(x[1][1]),尽管这件事的可能性几乎为零。
  • @DietrichEpp,你是对的,但在这种情况下,timestamp 已经是 str,因此字符串比较会快得多,而不是将它们转换为 int 并进行比较,因为转换是代价高昂的事情。
  • 非常感谢!
  • 对,只是指出比较是正确的,因为所有的值都有相同的位数。
【解决方案2】:

如果你想要一个排序的字典,那么使用来自collectionsOrderedDict

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

【讨论】:

  • 非常感谢!
猜你喜欢
  • 1970-01-01
  • 2011-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-23
  • 1970-01-01
  • 2022-10-17
  • 2012-05-10
相关资源
最近更新 更多