1

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]
} 
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245

4 Answers4

3

Note that dictionaries in general are not sortable. You can generate the internals sorted however without any lambdas by using itemgetter:

from operator import itemgetter
sorted_d = sorted(d.items(), key=itemgetter(1))

If you really want to maintain order, wrap the above in an OrderedDict

rvd
  • 558
  • 2
  • 9
1

The method sort() in Python is normally used on lists and tuples whereas sorted() is better for data structures like dictionaries.

In this case, using a simple lambda function can help you get what you want.

print(sorted(Beacon2.values(), key = lambda x: (x[0])) 
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Shawna
  • 11
  • 1
0

If you just want the values, use this:

sorted(data.values())

If you want the keys associated with the sorted values, use this:

sorted(data, key=data.get)

Both key and values:

sorted(data.items(), key=lambda x:x[1])

Courtesy of: sort dict by value python

jeevaa_v
  • 423
  • 5
  • 14
0

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.

RoadRunner
  • 25,803
  • 6
  • 42
  • 75