首頁 > 後端開發 > Python教學 > 如何檢索 Python 字典中的第一個條目?

如何檢索 Python 字典中的第一個條目?

DDD
發布: 2024-10-17 18:14:12
原創
497 人瀏覽過

How to Retrieve the First Entry in a Python Dictionary?

Retrieving the First Entry in a Dictionary

Indexing dictionaries by numerical indices, such as colors[0], will result in a KeyError since dictionaries are inherently unordered collections. However, Python 3.7 introduced order-preserving dictionaries, offering the ability to access elements in the order of insertion.

Indexing Dictionaries in Python 3.7+

In order-preserving dictionaries, the first key can be retrieved using:

<code class="python">first_key = list(colors.keys())[0]
first_value = list(colors.values())[0]</code>
登入後複製

This involves creating a list of the dictionary's keys or values and fetching the first element.

Alternate Method Using a Helper Function

To avoid creating a list, a helper function can be defined as follows:

<code class="python">def get_first_key(dictionary):
    for key in dictionary:
        return key
    raise IndexError</code>
登入後複製

Using the helper function:

<code class="python">first_key = get_first_key(colors)
first_value = colors[first_key]</code>
登入後複製

Indexing n-th Element

To retrieve the n-th key, a similar helper function can be employed:

<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
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板