Python select ith element in OrderedDict

In Python 2:

If you want to access the key:

>>> ordered_dict = OrderedDict([('a', 1), ('b', 2), ('c', 2), ('d', 1), ('e', 3)])
>>> ordered_dict.keys()[2]
'c'

If want to access the value:

>>> ordered_dict.values()[2]
2

If you're using Python 3, you can convert the KeysView object returned by the keys method by wrapping it as a list:

>>> list(ordered_dict.keys())[2]
'c'
>>> list(ordered_dict.values())[2]
2

Not the prettiest solution, but it works.


Using itertools.islice is efficient here, because we don't have to create any intermediate lists, for the sake of subscripting.

from itertools import islice
print(next(islice(ordered_dict.items(), 2, None)))

If you want just the value, you can do

print ordered_dict[next(islice(ordered_dict, 2, None))]