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

With OrderedDict you can use iterators

d = OrderedDict(a=1, b=2, c=3)
next(iter(d)) # returns 'a'
next(reversed(d) # returns 'c'

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)

If working with Python 3.6+ you can do a one liner:

First:

list({'fist': 1, 'second': 2, 'last': 3}.items())[0]
=> ('first', 1)

Last:

list({'fist': 1, 'second': 2, 'third': 3}.items())[-1]
=> ('third', 1)

This is the case because Python 3.6+ default dictionary preserves insertion order. This is also mentioned in the documentation:

Dictionaries preserve insertion order. Note that updating a key does not affect the order. Keys added after deletion are inserted at the end.

and

Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.


Python dictionaries are unordered, so "first" and "last" isn't defined. Instead, you can sort your keys, and then access the element associated with the first and last key in your sorted set.

EDIT:

The OP clarified that by "first" and "last" he meant the order in which keys were added to the dictionary. collections.OrderedDict should work for this case.