问题
I am creating a list of dicts, then I want to sort the dicts in the list by the value of the key, lowest to highest.
Everything works except the sort:
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)
I get the following output:
{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)}]
That sort order is incorrect, at least as far as how I think it should be sorted: by the value of the key in the dict, from lowest to highest.
回答1:
Using the keys in each dict as sort key works by converting them into a list:
>>> 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:
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)}]
来源:https://stackoverflow.com/questions/48568833/sort-a-list-of-dicts-by-each-dicts-key