45

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

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

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

d.??('b') 

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

4

5 回答 5

77

使用 OrderedDict: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
于 2013-01-26T16:36:07.173 回答
3

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

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]
于 2013-01-26T17:37:00.993 回答
1

No, there is no straightforward way because Python dictionaries do not have a set ordering.

From the documentation:

Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.

In other words, the 'index' of b depends entirely on what was inserted into and deleted from the mapping before:

>>> 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}

As of Python 2.7, you could use the collections.OrderedDict() type instead, if insertion order is important to your application.

于 2013-01-26T16:29:48.740 回答
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 :)
于 2021-01-25T13:13:26.443 回答
0

您可以简单地将字典发送到list,然后您可以选择您要查找的项目的索引。

DictTest = {
    '4000':{},
    '4001':{},
    '4002':{},
    '4003':{},
    '5000':{},
}

print(list(DictTest).index('4000'))
于 2021-10-05T17:26:40.773 回答