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

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

问题描述

我在下面有一个字典:

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 3.6 及以下版本的 Python 中是无序的.如果您不关心条目的顺序并希望通过索引访问键或值,您可以使用 keys = list(d),然后通过索引keys[i]访问列表中的key,以及d[keys[i]]的关联值.

Dictionaries are unordered in Python versions up to and including Python 3.6. If you do not care about the order of the entries and want to access the keys or values by index anyway, you can create a list of keys for a dictionary d using keys = list(d), and then access keys in the list by index keys[i], and the associated values with d[keys[i]].

如果您确实关心条目的顺序,从 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?)

在 Python 3.7 中,普通字典是有序的,所以你不再需要使用 OrderedDict(但你仍然可以 - 它基本上是相同的类型).Python 3.6 的 CPython 实现已包含该更改,但由于它不是语言规范的一部分,因此您不能在 Python 3.6 中依赖它.

In Python 3.7, normal dictionaries are ordered, so you don't need to use OrderedDict anymore (but you still can – it's basically the same type). The CPython implementation of Python 3.6 already included that change, but since it's not part of the language specification, you can't rely on it in Python 3.6.

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

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