按其他词典或列表对词典的自定义排序列表

2024-06-01 04:06:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字典列表,我想根据外部排序(列表、字典,任何有效的)来排序。假设我有以下列表:

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。我觉得我已经很接近了,但我还不能走到尽头


Tags: 列表字典排序haveorderkeysallwill
2条回答

试试这个:

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

相关问题 更多 >