按每个字典键对字典列表进行排序 [英] Sort a list of dicts by each dicts key

查看:85
本文介绍了按每个字典键对字典列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个字典列表,然后我想按键的值(从最低到最高)对列表中的字典进行排序。

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)

我得到以下输出:

{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.

推荐答案

将每个dict中的键用作排序键,可以将它们转换为列表:

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

这篇关于按每个字典键对字典列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆