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

DDD
发布: 2024-10-17 18:14:12
原创
348 人浏览过

How to Retrieve the First Entry in a Python Dictionary?

检索字典中的第一个条目

通过数字索引(例如颜色[0])对字典进行索引将导致 KeyError,因为字典本质上是无序的集合。然而,Python 3.7 引入了保序字典,提供了按插入顺序访问元素的能力。

Python 3.7 中的索引字典

在保序字典中,可以使用以下方法检索第一个键:

<code class="python">first_key = list(colors.keys())[0]
first_value = list(colors.values())[0]</code>
登录后复制

这涉及创建字典的键或值的列表并获取第一个元素。

使用辅助函数的替代方法

为了避免创建列表,可以如下定义辅助函数:

<code class="python">def get_first_key(dictionary):
    for key in dictionary:
        return key
    raise IndexError</code>
登录后复制

使用辅助函数:

<code class="python">first_key = get_first_key(colors)
first_value = colors[first_key]</code>
登录后复制

索引第 n 个元素

要检索第 n 个键,可以使用类似的辅助函数:

<code class="python">def get_nth_key(dictionary, n=0):
    if n < 0:
        n += len(dictionary)
    for i, key in enumerate(dictionary.keys()):
        if i == n:
            return key
    raise IndexError("dictionary index out of range")</code>
登录后复制

以上是如何检索 Python 字典中的第一个条目?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!