Home  >  Article  >  Backend Development  >  How to Access the First and N-th Key-Value Pairs in a Python Dictionary?

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

Barbara Streisand
Barbara StreisandOriginal
2024-10-17 18:08:03800browse

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

Getting the First Entry in a Python Dictionary

Indexing dictionaries using numerical indices, like colors[0], can lead to KeyError exceptions. Dictionaries preserve insertion order from Python 3.7 onwards, enabling us to work with them like ordered collections.

Acquiring the First Key and Value

To obtain the first key and value in a dictionary, we can utilize the following methods:

  • List Conversion: Create a list of keys or values using list(dict.keys()) or list(dict.values()) and access the first element.
<code class="python">first_key = list(colors)[0]
first_val = list(colors.values())[0]</code>
  • Looping with Index: Iterate through the dictionary and return the first key or value encountered.
<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 an N-th Key

To retrieve an arbitrary key at index n, implement the following 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>

The above is the detailed content of How to Access the First and N-th Key-Value Pairs in a Python Dictionary?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn