Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python select ith element in OrderedDict

Tags:

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.)

like image 741
Pingk Avatar asked Mar 24 '14 13:03

Pingk


People also ask

How do you slice in OrderedDict?

You can use the itertools. islice function, which takes an iterable and outputs the stop first elements. This is beneficial since iterables don't support the common slicing method, and you won't need to create the whole items list from the OrderedDict.

How do I get the first key from an ordered dictionary?

By the first key, we mean the key saved in the first index of the dictionary. In Python versions 3.7 and above, where a dictionary is ordered, we can get the first key, by first converting the dictionary into an iterated object using iter() function and then fetching its first index key using the next function.

What is the difference between dict and OrderedDict?

The OrderedDict is a subclass of dict object in Python. The only difference between OrderedDict and dict is that, in OrderedDict, it maintains the orders of keys as inserted. In the dict, the ordering may or may not be happen. The OrderedDict is a standard library class, which is located in the collections module.

Is OrderedDict sorted?

The OrderedDict() is a method of the collections module that returns an instance of a dict subclass with a method specialized for rearranging dictionary order. The sorted() function returns a sorted list of the specified iterable object. The OrderedDict() method preserves the order in which the keys are inserted.


1 Answers

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.

like image 109
Daniel Lee Avatar answered Sep 30 '22 08:09

Daniel Lee