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

cha*_*er3 20 python indexing dictionary key python-2.7

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

d = { 'a': 10, 'b': 20, 'c': 30}
Run Code Online (Sandbox Code Playgroud)

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

d.??('b') 
Run Code Online (Sandbox Code Playgroud)

我知道它可以通过循环或lambda(嵌入循环)来实现.只是觉得应该有一个更直截了当的方式.

Kiw*_*uce 43

使用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
Run Code Online (Sandbox Code Playgroud)

对于那些使用Python 3的人

>>> list(x.keys()).index("c")
1
Run Code Online (Sandbox Code Playgroud)

  • 很好的解决方案,但是,我想知道获取索引的复杂性(可能是 O(n))。我们可以通过索引值 > 或至少键或值来获取键值对。 (2认同)