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

2024-04-20 04:17:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python字典的键,我想在字典中得到相应的索引。假设我有下列字典

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

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

d.??('b') 

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


Tags: 方法lambda函数字典情况键值
3条回答

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

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.

换言之,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}

从Python2.7开始,如果插入顺序对应用程序很重要,则可以使用^{} type

使用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中的字典没有顺序。您可以使用元组列表作为数据结构。

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]

相关问题 更多 >