Python select ith element in OrderedDict -


i have snippet of code orders dictionary alphabetically. there way select ith key in ordered dictionary , return 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 have function along vein of...

select = int(input("input dictionary index")) #user inputs 2 #program looks 2nd entry in ordered_dict (c in case) #and returns value of c (2 in case) 

how can achieved? thanks.

(similar accessing items in ordereddict, want output value of key-value pair.)

in python 2:

if want access key:

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

if want access value:

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

if you're using python 3, can convert keysview object returned keys method wrapping list:

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

not prettiest solution, works.


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -