Python:获取字典中索引的键 [英] Python: get key of index in dictionary

查看:3425
本文介绍了Python:获取字典中索引的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
逆字典查找-Python
字典与Python的反向映射

Possible Duplicate:
Inverse dictionary lookup - Python
reverse mapping of dictionary with Python

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

How do i get key of index in dictionary?

例如:

i = {'a': 0, 'b': 1, 'c': 2}

因此,如果我想获取i [0]的密钥,它将返回'a'

so if i want to get key of i[0], it will return 'a'

推荐答案

可以执行以下操作:

i={'foo':'bar', 'baz':'huh?'}
keys=i.keys()  #in python 3, you'll need `list(i.keys())`
values=i.values()
print keys[values.index("bar")]  #'foo'

但是,每次更改字典时,都需要更新键,值,因为字典在3.7之前的Python版本中没有排序.在这些版本中,每当您插入新的键/值对时,您原先认为的订单就会消失,并被新的(或多或少随机)订单代替.因此,在字典中要求索引是没有意义的.

However, any time you change your dictionary, you'll need to update your keys,values because dictionaries are not ordered in versions of Python prior to 3.7. In these versions, any time you insert a new key/value pair, the order you thought you had goes away and is replaced by a new (more or less random) order. Therefore, asking for the index in a dictionary doesn't make sense.

从Python 3.6开始,对于Python的CPython实现,词典会记住插入项目的顺序.从Python 3.7开始,字典按插入顺序排序.

还请注意,您要问的可能不是您真正想要的.不能保证字典中的逆映射是唯一的.换句话说,您可以使用以下字典:

Also note that what you're asking is probably not what you actually want. There is no guarantee that the inverse mapping in a dictionary is unique. In other words, you could have the following dictionary:

d={'i':1, 'j':1}

在这种情况下,无法知道您想要的是i还是j,实际上,这里没有答案可以告诉您要选择哪个('i''j')(再次,因为字典是无序的).您想在这种情况下发生什么?您可以得到可接受键的列表...但是我想您对字典的基本理解不太正确.

In that case, it is impossible to know whether you want i or j and in fact no answer here will be able to tell you which ('i' or 'j') will be picked (again, because dictionaries are unordered). What do you want to happen in that situation? You could get a list of acceptable keys ... but I'm guessing your fundamental understanding of dictionaries isn't quite right.

这篇关于Python:获取字典中索引的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆