我有一个像 {'james': 32, 'jacob': 43, 'marie': 3}
这样的字典。
假设我有一个像 ['marie', 'jacob', 'james']
这样的列表,我如何对字典进行排序,以便新字典按项目的顺序排序在列表中?
即结果:
{'marie': 3, 'jacob': 43, 'james': 32}
最佳答案
你不能对字典进行排序,但你可以使用 collections.OrderedDict
这里:
>>> from collections import OrderedDict
>>> from operator import itemgetter
>>> lst = ['marie', 'jacob', 'james']
>>> d = {'james': 32, 'jacob': 43, 'marie': 3}
>>> OrderedDict(zip(lst, itemgetter(*lst)(d)))
OrderedDict([('marie', 3), ('jacob', 43), ('james', 32)])
关于python - 按列表中项目的顺序对 python 字典进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24985965/