Home > Article > Backend Development > How to Access the First and N-th Key-Value Pairs 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.
To obtain the first key and value in a dictionary, we can utilize the following methods:
<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>
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!