python - 从字典中获取值索引

标签 python python-2.7 dictionary indices

我有一个OrderedDict:

from collections import OrderedDict
d = OrderedDict([('r', 1), ('s', 5), ('a', 3), ('n', 7), ('y', 2)])

我想根据值范围获取字典值的索引。例如,字典 d 的索引应该是数组(或 np.array),如下所示:

indices
array([ 0, 3, 2, 4, 1 ], dtype=int64) 

索引4是字典中的最大值,索引0是最小值

我试过了:

indices = np.argsort(d.values)

最佳答案

您可以使用列表理解来实现这一点:

>>> values = d.values()
>>> sorted_values = sorted(values)
>>> [sorted_values.index(item) for item in values]
[0, 3, 2, 4, 1]

关于python - 从字典中获取值索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37047692/

相关文章:

python - python中的共享内存并行处理

python - 在 xmltodict 中捕获 ExpatError

python - Python 的列表、元组和字典的 Node.js 等效数据类型

c++ - 如何查找给定键是否存在于 C++ std::map 中

Python pandas - 在 groupby 之后过滤行

python - Plotly Express 悬停选项

python-3.x - 在脚本本身内部获取shell/python脚本的PID

python - 在速度方面改进 python 代码

python - 当其他两列的元组唯一时,Pandas 添加新列并用列表中的项目填充它

python - 更新 QGraphicsItem 的不透明度