我有一个字典列表,我想根据外部排序来排序(列表,字典,不管用什么方法)。假设我有以下列表:
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
。我觉得我已经接近了,但我还没结束。
答案 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]))