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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14538885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:45:56  来源:igfitidea点击:

How to get the index with the key in Python dictionary?

pythonpython-2.7dictionaryindexingkey

提问by chapter3

I have the key of a python dictionary and I want to get the corresponding index in the dictionary. Suppose I have the following dictionary,

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

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

Is there a combination of python functions so that I can get the index value of 1, given the key value 'b'?

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

d.??('b') 

I know it can be achieved with a loop or lambda (with a loop embedded). Just thought there should be a more straightforward way.

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

采纳答案by Kiwisauce

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

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

For those using Python 3

对于那些使用 Python 3 的人

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

回答by Martijn Pieters

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

不,没有直接的方法,因为 Python 字典没有固定的顺序。

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.

键和值以非随机的任意顺序列出,因 Python 实现而异,并取决于字典的插入和删除历史。

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

换句话说,的“索引”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}

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

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

回答by Matt Alcock

Dictionaries in python have no order. You could use a list of tuples as your data structure instead.

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

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

Then this code could be used to find the locations of keys with a specific value

然后此代码可用于查找具有特定值的键的位置

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

>>> [1]