如何索引到字典? [英] How to index into a dictionary?

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

问题描述

我在下面有一个词典:

colors = {
    "blue" : "5",
    "red" : "6",
    "yellow" : "8",
}

如何索引字典中的第一个条目?

How do I index the first entry in the dictionary?

colors [0] 将出于显而易见的原因,返回 KeyError

colors[0] will return a KeyError for obvious reasons.

推荐答案

字典在Python中是无序的。如果你不关心条目的顺序并且想要通过索引访问键或值,你可以使用 d.keys()[i] d.values()[i] d.items()[i] 。 (请注意,这些方法分别创建了所有键,值或项的列表。因此,如果您需要它们多一次,请将列表存储在变量中以提高性能。)

Dictionaries are unordered in Python. If you do not care about the order of the entries and want to access the keys or values by index anyway, you can use d.keys()[i] and d.values()[i] or d.items()[i]. (Note that these methods create a list of all keys, values or items, respectively. So if you need them more then once, store the list in a variable to improve performance.)

如果您关心条目的顺序,从Python 2.7开始,您可以使用 collections.OrderedDict 。或者使用成对列表

If you do care about the order of the entries, starting with Python 2.7 you can use collections.OrderedDict. Or use a list of pairs

l = [("blue", "5"), ("red", "6"), ("yellow", "8")]

如果您不需要访问权限键。 (顺便提一下,为什么你的数字串?)

if you don't need access by key. (Why are your numbers strings by the way?)

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

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