我正在创建一个dicts列表,然后我想按键的值从最低到最高的顺序对列表中的dicts进行排序。
除了排序外,一切正常:
def pythagorean(x1, y1, x2=0, y2=0):
return ((x1 - x2)**2 + (y1 - y2)**2)**0.5
points = [(-2, -4), (0, -2), (-1, 0), (3, -5), (-2, -3), (3, 2)]
dicts = []
for coord in points:
d = {}
a1, b1 = coord
distance = pythagorean(a1, b1)
d[distance] = (a1, b1)
dicts.append(d)
for i in dicts:
print(i)
dist_list = []
for item in dicts:
for key in item:
dist_list.append(key)
temp = sorted(dicts, key=lambda d: [k in d for k in dist_list])
print(temp)
我得到以下输出:
{4.47213595499958: (-2, -4)}
{2.0: (0, -2)}
{1.0: (-1, 0)}
{5.830951894845301: (3, -5)}
{3.605551275463989: (-2, -3)}
{3.605551275463989: (3, 2)}
[4.47213595499958, 2.0, 1.0, 5.830951894845301, 3.605551275463989, 3.605551275463989]
[{3.605551275463989: (-2, -3)},
{3.605551275463989: (3, 2)},
{5.830951894845301: (3, -5)},
{1.0: (-1, 0)},
{2.0: (0, -2)},
{4.47213595499958: (-2, -4)}]
那个排序顺序是不正确的,至少就我认为它应该如何排序而言:通过dict中键的值,从最低到最高。
答案 0 :(得分:2)
This is one way:
lst = [{3.605551275463989: (-2, -3)}, {3.605551275463989: (3, 2)},
{5.830951894845301: (3, -5)}, {1.0: (-1, 0)},
{2.0: (0, -2)}, {4.47213595499958: (-2, -4)}]
list(map(dict, sorted(list(i.items()) for i in lst)))
# [{1.0: (-1, 0)},
# {2.0: (0, -2)},
# {3.605551275463989: (-2, -3)},
# {3.605551275463989: (3, 2)},
# {4.47213595499958: (-2, -4)},
# {5.830951894845301: (3, -5)}]
答案 1 :(得分:0)
使用每个dict中的键作为排序键,将它们转换为列表:
>>> sorted(dicts, key=lambda d: list(d.keys()))
[{1.0: (-1, 0)},
{2.0: (0, -2)},
{3.605551275463989: (-2, -3)},
{3.605551275463989: (3, 2)},
{4.47213595499958: (-2, -4)},
{5.830951894845301: (3, -5)}]
答案 2 :(得分:0)
正如@Mike所说,诀窍是将进行list()
或dict.keys()
的结果转换为dict.values()
。否则,您将得到以下错误之一:
TypeError: 'dict_keys' object is not subscriptable
TypeError: 'dict_values' object is not subscriptable
我要在此处添加一个简洁的复制/意大利面演示,以帮助Google进行访问。
import logging
# sort by keys
sorted(
[
{ level: getattr(logging, level) }
for level in
['WARNING', 'WARN', 'NOTSET', 'INFO', 'FATAL', 'ERROR', 'DEBUG', 'CRITICAL']
],
key=lambda o:list(o.keys())[0]
)
# returns:
# [
# {'CRITICAL': 50}, {'DEBUG': 10}, {'ERROR': 40}, {'FATAL': 50},
# {'INFO': 20}, {'NOTSET': 0}, {'WARN': 30}, {'WARNING': 30}
# ]
# sort by values
sorted(
[
{ level: getattr(logging, level) }
for level in
['WARNING', 'WARN', 'NOTSET', 'INFO', 'FATAL', 'ERROR', 'DEBUG', 'CRITICAL']
],
key=lambda o:list(o.values())[0]
)
# returns:
# [
# {'NOTSET': 0}, {'DEBUG': 10}, {'INFO': 20}, {'WARNING': 30},
# {'WARN': 30}, {'ERROR': 40}, {'FATAL': 50}, {'CRITICAL': 50}
# ]