Skip to content Skip to sidebar Skip to footer

Python: How To Sort A Dictionary Of X And Y Coordinates By Ascending X Coordinate Value?

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 diff

Solution 1:

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

Solution 2:

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

Solution 3:

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.

Solution 4:

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

Post a Comment for "Python: How To Sort A Dictionary Of X And Y Coordinates By Ascending X Coordinate Value?"