如何在 Python 3.7 及更高版本中依序索引字典

Barbara Streisand
發布: 2024-10-17 18:10:02
原創
768 人瀏覽過

How to Index into a Dictionary Sequentially in Python 3.7 and Later

Indexing into a Dictionary: A Python 3.7 and Later Approach

In a dictionary, accessing values by key is the typical operation. However, in some cases, it may be desirable to index into a dictionary's entries sequentially as if it were a list. However, unlike lists, dictionaries do not have an inherent ordering.

Pre-Python 3.7 Dictionaries

In Python versions prior to 3.7, dictionaries were not ordered, and accessing the first entry using an index like colors[0] would result in a KeyError.

Ordered Dictionaries in Python 3.7 and Later

Starting with Python 3.7, dictionaries have become order-preserving, meaning they maintain the order of insertion. This behavior is similar to an OrderedDict from the collections module.

Accessing the First Entry

Despite the new ordering, there is still no dedicated method for indexing into a dictionary's keys or values directly. However, the following approaches can be used:

  • Convert to a List: Create a list of either the keys or values and access the first item like this:
<code class="python">first_key = list(colors)[0]
first_val = list(colors.values())[0]</code>
登入後複製
  • Use a Custom Function: Define a helper function to iterate over the keys, returning the desired entry based on its index:
<code class="python">def get_first_key(dictionary):
    for key in dictionary:
        return key
    raise IndexError

first_key = get_first_key(colors)
first_val = colors[first_key]</code>
登入後複製

Accessing the nth Entry

For indexing into keys or values beyond the first, a similar custom function approach can be used:

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

By using these approaches, you can index into dictionaries in a manner similar to lists, even though dictionaries are not inherently ordered.

以上是如何在 Python 3.7 及更高版本中依序索引字典的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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