python - 按列表中项目的顺序对 python 字典进行排序

标签 python list dictionary

我有一个像 {'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/

相关文章:

python - Pandas、Excel 导入和多重索引

Python - 导入全局/站点包模块而不是本地目录中的同名文件

python - 使用 Pytest 和 Mock 测试查询数据库的 View

java - 如何在 Java 8 中使用 CSV 值作为构造函数参数

python - 如何自动清除python中的变量?

for 中的 Javascript 动态事件

python - 如何将字典+列表组合成一个排序列表

c# - Dictionary<X, Func<Y>> 从其中的 Func<> 访问包含的 Dictionary

java - 处理 2 个 map 中的数据以创建第 3 个 map

java - 获取 ArrayIndexOutOfBoundsException : 3 while executing Hadoop Pragram on cloudera