Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the first and the last elements in a dictionary?

Before posting, I have already gone through Access an arbitrary element in a dictionary in Python, butI'm uncertain about this.

I have a long dictionary and I've to get the values of its first and last keys. I can use dict[dict.keys()[0]] and dict[dict.keys()[-1]] to get the first and last elements, but since the key:value pairs are outputted in a random form(as in the positioning of the key:value pairs is random), will the solution provided in this link always work?

like image 541
PythonEnthusiast Avatar asked Sep 26 '13 13:09

PythonEnthusiast


People also ask

How do you access elements in a dictionary?

Accessing Elements from DictionaryKeys can be used either inside square brackets [] or with the get() method. If we use the square brackets [] , KeyError is raised in case a key is not found in the dictionary. On the other hand, the get() method returns None if the key is not found.

How do you find the first element in a dictionary?

Get first value in a dictionary using item() item() function of dictionary returns a view of all dictionary in form a sequence of all key-value pairs. From this sequence select the first key-value pair and from that select first value.

What part of a dictionary that shows the first or last item on that page?

Also called headword, guide word. a word printed at the top of a page in a dictionary or other reference book to indicate the first or last entry or article on that page.


1 Answers

Use an OrderedDict, because a normal dictionary doesn't preserve the insertion order of its elements when traversing it. Here's how:

# import the right class from collections import OrderedDict  # create and fill the dictionary d = OrderedDict() d['first']  = 1 d['second'] = 2 d['third']  = 3  # retrieve key/value pairs els = list(d.items()) # explicitly convert to a list, in case it's Python 3.x  # get first inserted element  els[0] => ('first', 1)  # get last inserted element  els[-1] => ('third', 3) 
like image 70
Óscar López Avatar answered Oct 03 '22 18:10

Óscar López