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

时间:2013-01-26 16:23:39

标签: python python-2.7 dictionary indexing key

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

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

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

d.??('b') 

我知道可以使用循环或lambda(嵌入循环)来实现。只是觉得应该有一种更直接的方式。

4 个答案:

答案 0 :(得分:38)

使用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

答案 1 :(得分:1)

python中的字典没有顺序。您可以使用元组列表作为数据结构。

d = { 'a': 10, 'b': 20, 'c': 30}
newd = [('a',10), ('b',20), ('c',30)]

然后,此代码可用于查找具有特定值

的键的位置
locations = [i for i, t in enumerate(newd) if t[0]=='b']

>>> [1]

答案 2 :(得分:0)

不,没有简单的方法,因为Python词典没有集合排序。

来自documentation

  

键和值以任意顺序列出,这是非随机的,在Python实现中各不相同,并且取决于字典的插入和删除历史。

换句话说,b的'索引'完全取决于之前在映射中插入和删除的内容:

>>> map={}
>>> map['b']=1
>>> map
{'b': 1}
>>> map['a']=1
>>> map
{'a': 1, 'b': 1}
>>> map['c']=1
>>> map
{'a': 1, 'c': 1, 'b': 1}

从Python 2.7开始,如果插入顺序对您的应用程序很重要,则可以使用collections.OrderedDict() type

答案 3 :(得分:0)

#Creating dictionary
animals = {"Cat" : "Pat", "Dog" : "Pat", "Tiger" : "Wild"}

#Convert dictionary to list (array)
keys = list(animals)

#Printing 1st dictionary key by index
print(keys[0])

#Done :)