[英]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 different orders). 我有以下字典,希望根据它们的X坐标以升序进行排序,以便我可以通过颜色排列(RGB以不同顺序)来识别“信标”。 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]
}
Note that dictionaries in general are not sortable. 请注意,字典通常无法排序。 You can generate the internals sorted however without any lambdas by using
itemgetter
: 您可以使用
itemgetter
生成排序后的内部函数,但不包含任何lambda:
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
如果您真的想维护订单,请将以上内容包装在
OrderedDict
The method sort() in Python is normally used on lists and tuples whereas sorted() is better for data structures like dictionaries. Python中的sort()方法通常用于列表和元组,而sorted()更适合于字典等数据结构。
In this case, using a simple lambda function can help you get what you want. 在这种情况下,使用简单的lambda函数可以帮助您获得所需的内容。
print(sorted(Beacon2.values(), key = lambda x: (x[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 礼貌: 按值python排序dict
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. 首先在
Beacon2.items()
中对元组列表进行排序的Beacon2.items()
,并在每个元组的[1][0]
的X坐标上应用了排序键。
Note that you need to wrap an OrderedDict
to your result to preserve order of the dictionary. 请注意,您需要将
OrderedDict
包装到结果中以保留字典的顺序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.