Skip to content Skip to sidebar Skip to footer

Python3, Ordering A Complex Dict

I've got a complex Python dictionary that stores the following values: MAC ADDRESS, RSSI and TIMESTAMP: beacons_detected = { '55:c1:9a:41:4c:b9': ['-78', '1493580469'], '9c

Solution 1:

sort the dictionary from smallest to largest:

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

sort the dictionary from largest to smallest:

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

Solution 2:

If you want a sorted dictionary, then use the OrderedDict from 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'])])

And the access is same as dict:

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

Post a Comment for "Python3, Ordering A Complex Dict"