Python selects ith element in OrderedDict

I have a code snippet that arranges a dictionary alphabetically. Is there a way to select the ith key in an 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 ...

 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 Elements in orderdict , but I only want to output the value of the key-value pair.)

+7
python ordereddictionary
source share
4 answers

In Python 2:

If you want to access the key:

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

If you want to access the value:

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

If you are 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 nicest solution, but it works.

+12
source share

Using itertools.islice is effective here because we do not need to create staging lists for the sake of subscription.

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

If you want just value, you can do

 print ordered_dict[next(islice(ordered_dict, 2, None))] 
+8
source share

Do you need to use OrderedDict or just need a type of type dict that supports indexing? If the latter, then consider a sorted dict object. Some implementations of SortedDict (which orders pairs based on the sort order of the keys) support fast nth indexing. For example, the sortedcontainers project has a random access indexed SortedDict .

In your case, it will look something like this:

 >>> from sortedcontainers import SortedDict >>> sorted_dict = SortedDict(a=1, b=2, c=2, d=1, e=3) >>> print sorted_dict.iloc[2] 'c' 

If you do a lot of searches, it will be much faster than repeating the required index again.

+5
source share

Don't underestimate the simple "ole for loop:

 from collections import OrderedDict od=OrderedDict([('a', 1), ('b', 2), ('c', 2), ('d', 1), ('e', 3)]) def ith(od, tgt): for i, t in enumerate(od.items()): if i==tgt: print('element {}\ key is "{}"'.format(i,t[0])) break else: print('element {} not found'.format(tgt)) ith(od, 2) # element 2 key is "c" ith(od, 20) # element 20 not found 

The advantage is that the cycle will break as soon as the desired element is found, and will return a reasonable result if not found ...

The disadvantage is that relative slices are not supported.

0
source share

All Articles