如何存取Python字典中的第一個和第N個鍵值對?

Barbara Streisand
發布: 2024-10-17 18:08:03
原創
717 人瀏覽過

How to Access the First and N-th Key-Value Pairs in a Python Dictionary?

取得 Python 字典中的第一個條目

使用數字索引(如顏色[0])對字典進行索引可能會導致 KeyError 異常。從 Python 3.7 開始,字典保留了插入順序,使我們能夠像有序集合一樣使用它們。

取得第一個鍵和值

要取得字典中的第一個鍵和值,我們可以使用以下方法:

  • 列表轉換:使用list(dict.keys()) 或list(dict.values()) 建立鍵或值列表並存取第一個元素。
<code class="python">first_key = list(colors)[0]
first_val = list(colors.values())[0]</code>
登入後複製
  • 使用索引循環:迭代字典並傳回遇到的第一個鍵或值。
<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>
登入後複製

存取第 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字典中的第一個和第N個鍵值對?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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