Python select ith element in OrderedDict

Pingk picture Pingk · Mar 24, 2014 · Viewed 20.2k times · Source

I have a snippet of code which orders a dictionary alphabetically. Is there a way to select the ith key in the ordered dictionary and return its corresponding value? i.e.

import collections
initial = dict(a=1, b=2, c=2, d=1, e=3)
ordered_dict = collections.OrderedDict(sorted(initial.items(), key=lambda t: t[0]))
print(ordered_dict)

OrderedDict([('a', 1), ('b', 2), ('c', 2), ('d', 1), ('e', 3)])

I want to have some function along the vein of...

select = int(input("Input dictionary index"))
#User inputs 2
#Program looks up the 2nd entry in ordered_dict (c in this case)
#And then returns the value of c (2 in this case)

How can this be achieved? Thanks.

(Similar to Accessing Items In a ordereddict, but I only want to output the value of the key-value pair.)

Answer

Daniel Lee picture Daniel Lee · Mar 24, 2014

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.