Python 辞書の最初のエントリを取得するにはどうすればよいですか?

DDD
リリース: 2024-10-17 18:14:12
オリジナル
349 人が閲覧しました

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 中国語 Web サイトの他の関連記事を参照してください。

ソース:php
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!