【发布时间】:2014-09-30 16:56:48
【问题描述】:
我有两个列表。我的第一个列表 first_list_ordered 包含字符串。
first_list_ordered = ["id1", "id2", "id3", "id4", "id5", "id6", "id7"]
我的第二个列表second_list_unsorted 包含至少有一个名为id 的键的字典,其中的值可能出现在first_list_ordered 中。
second_list_unordered = [{"id": "id6", "content": "sth"},
{"id": "id4", "content": "sth"},
{"id": "id1", "content": "sth"},
{"id": "id3", "content": "sth"}]
现在我想按照id 在第一个列表中的值的出现顺序对第二个列表进行排序。
结果应如下所示:
result = [{"id": "id1", "content": "sth"},
{"id": "id3", "content": "sth"},
{"id": "id4", "content": "sth"},
{"id": "id6", "content": "sth"}]
因此,如果您为second_list_unordered 中的每个字典创建所有值id 的列表,您将获得first_list_ordered 的无序子集。
我的方法如下:
>>> first_list_ordered = ["id1", "id2", "id3", "id4", "id5", "id6", "id7"]
>>> second_list_unordered = [{"id": "id6", "content": "sth"}, {"id": "id4", "content": "sth"}, {"id": "id1", "content": "sth"}, {"id": "id3", "content": "sth"}]
>>> indices = {c: i for i, c in enumerate(first_list_ordered)}
>>> result = sorted(second_list_unordered, key=indices.get)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
显然它不能那样工作......现在我被卡住了。
感谢任何提示!
【问题讨论】:
标签: python list sorting python-3.x dictionary