【发布时间】:2020-08-04 18:42:18
【问题描述】:
我有一个字典列表,我想根据外部排序(列表、字典、任何有效的)进行排序。假设我有以下列表:
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。我觉得我已经接近了,但我还不能走到最后。
【问题讨论】:
-
您的问题是“给定一个键值对
x作为字典,我如何获取键?”? -
@Asocia 如果有多个键怎么办?
-
@deadshot 我专门要求只提供一个键值对,但没关系,我想通了,哈哈:D
标签: python python-3.x list sorting dictionary