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.)
Using
itertools.islice
is efficient here, because we don't have to create any intermediate lists, for the sake of subscripting.If you want just the value, you can do
You could do something along these lines (od is the ordered dict):
Don't underestimate just a plain 'ole for loop:
The advantage here is that the loop will break as soon as the desired element is found and returns a sensible result if not found...
The disadvantage is that relative slices are not supported.
In Python 2:
If you want to access the key:
If want to access the value:
If you're using Python 3, you can convert the
KeysView
object returned by thekeys
method by wrapping it as a list:Not the prettiest solution, but it works.
Do you have to use an OrderedDict or do you just want a dict-like type that supports indexing? If the latter, then consider a sorted dict object. Some implementations of SortedDict (which orders pairs based on the key sort order) support fast n-th indexing. For example, the sortedcontainers project has a SortedDict type with random-access indexing.
In your case it would look something like:
If you do a lot of lookups, this will be a lot faster than repeatedly iterating to the desired index.