I have the following dictionary that I would like to sort based on their X coordinate in ascending fashion so that I can identify the "beacon" by the color arrangement (RGB in different orders). I keep trying to sort it like a list but that's not working out too well. Thanks in advance :)
Beacon2 = {
'r': [998.9282836914062, 367.3825378417969],
'b': [985.82373046875, 339.2225646972656],
'g': [969.539794921875, 369.2041931152344]
}
For this specific dictionary the expected result is
sortedBeacon = {
'g': [969.539794921875, 369.2041931152344],
'b': [985.82373046875, 339.2225646972656],
'r': [998.9282836914062, 367.3825378417969]
}
解决方案
You can try this:
from collections import OrderedDict
Beacon2 = {'r': [998.9282836914062, 367.3825378417969], 'b':
[985.82373046875, 339.2225646972656], 'g': [969.539794921875, 369.2041931152344]}
sorted_beacons = sorted(Beacon2.items(), key = lambda x: x[1][0])
>>> print(OrderedDict(sorted_beacons))
OrderedDict([('g', [969.539794921875, 369.2041931152344]), ('b', [985.82373046875, 339.2225646972656]), ('r', [998.9282836914062, 367.3825378417969])])
Where you first sort the list of tuples from Beacon2.items(), with a sorting key applied on the X coordinate located at [1][0] of each tuple.
Note that you need to wrap an OrderedDict to your result to preserve order of the dictionary.