根据其他字典或列表对字典进行自定义排序的列表

时间:2020-08-04 18:42:18

标签: python python-3.x list sorting dictionary

我有一个字典列表,我想根据外部排序来排序(列表,字典,不管用什么方法)。假设我有以下列表:

list_a = [{"dylan": "alice"}, {"arnie": "charles"}, {"chelsea": "bob"}]

我想这样排序

sorted_list_a = [{"arnie": "charles"}, {"chelsea": "bob"}, {"dylan": "alice"}]

我试图这样做:

# list_a will have a variable number of dictionaries all with unique keys
# list_order will have all dictionary keys ordered, even if they don't appear in list_a
list_order = [{"arnie": 1}, {"britta": 2}, {"chelsea": 3}, {"dylan": 4}]
list_a.sort(key=lambda x: list_order[x.keys()])

但是我得到TypeError: list indices must be integers or slices, not dict_keys。我觉得我已经接近了,但我还没结束。

2 个答案:

答案 0 :(得分:0)

尝试一下:

def fun(x):
    k, = (x)
    for d in list_order:
        if k in d:
            return d[k]

res = sorted(list_a, key=fun)
print(res)

输出:

[{'arnie': 'charles'}, {'chelsea': 'bob'}, {'dylan': 'alice'}]

答案 1 :(得分:-1)

  l = [{"dylan": "alice"}, {"arnie": "charles"}, {"chelsea": "bob"}]
d={}
for i in l:
    for x,y in (i.items()):
       d[x]=y
print(sorted(d.items(),key=lambda x: x[0]))