Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

python - Sort a list of dicts by each dicts key

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...