python - 如何使用字典中的键获取索引?

标签 python python-2.7 dictionary indexing key

我有一个 python 字典的键,我想在字典中获取相应的索引。假设我有以下字典,

d = { 'a': 10, 'b': 20, 'c': 30}

在给定键值'b'的情况下,是否有python函数的组合,以便我可以获得索引值1?

d.??('b') 

我知道它可以通过循环或 lambda(嵌入循环)来实现。只是觉得应该有更直接的方法。

最佳答案

使用 OrderedDicts:http://docs.python.org/2/library/collections.html#collections.OrderedDict

>>> x = OrderedDict((("a", "1"), ("c", '3'), ("b", "2")))
>>> x["d"] = 4
>>> x.keys().index("d")
3
>>> x.keys().index("c")
1

对于那些使用 Python 3 的人

>>> list(x.keys()).index("c")
1

关于python - 如何使用字典中的键获取索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14538885/

相关文章:

python - 如何使用子文件夹模板在 cookiecutter 模板中创建多个子文件夹

python - 首选项窗口在关闭时销毁 - Glade、Gtk、Python

python - 如何从gensim的word2vec中提取词汇向量?

python - tastypie 从非 pk 字段访问数据

python-2.7 - 无法将图形另存为 .eps [无法识别 gswin32c]

iphone - 离线 iPhone map 与离线路线

python - python 查找并比较两个日期时间列表的最小时间增量

python - 将参数传递给 python 二进制可执行文件

python - 从嵌套字典创建列表

jquery - JVectorMap 的 map ?