如何從保留順序的 Python 字典中檢索鍵

Patricia Arquette
發布: 2024-10-17 18:11:02
原創
784 人瀏覽過

How to Retrieve Keys from Order-Preserving Python Dictionaries

Indexing into a Dictionary: Understanding the Order Preservation Feature

In Python, dictionaries are used to store key-value pairs, and traditionally, these dictionaries were unordered. However, with the introduction of Python 3.7, dictionaries gained an order-preserving feature, behaving similarly to OrderedDicts.

While this feature eliminates the ability to directly index dictionaries using an integer index (e.g., colors[0]), it opens up alternative approaches to retrieve the first or n-th key in a dictionary.

Retrieving the First Key and Value

To obtain the first key in the dictionary, you can convert the dictionary keys to a list and access the first element:

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

Similarly, to get the first value, convert the dictionary values to a list and access the first element:

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

An Alternative Method for Retrieving the First Key

If you don't want to create a list, you can use a helper function to iterate through the dictionary keys and return the first one:

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

Using this function, you can retrieve the first key as follows:

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

Retrieving the n-th Key

To retrieve the n-th key, you can use a modified version of the get_first_key function:

<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>
登入後複製

With this function, you can retrieve the n-th key as:

<code class="python">first_key = get_nth_key(colors, n=1)  # retrieve the second key</code>
登入後複製

Note that these methods rely on iterating through the dictionary, which can be inefficient for large dictionaries.

以上是如何從保留順序的 Python 字典中檢索鍵的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!